Skip to content

Instantly share code, notes, and snippets.

@rose-pace
Last active October 5, 2016 20:30
Show Gist options
  • Select an option

  • Save rose-pace/7fce1641c738d01e88eaeedcef12f6e1 to your computer and use it in GitHub Desktop.

Select an option

Save rose-pace/7fce1641c738d01e88eaeedcef12f6e1 to your computer and use it in GitHub Desktop.
Converts JSON data into MVC .Net consumable fields and synchronously posts to a set path.
// Performs a synchronous post that changes json to .Net consumable post fields
// this will send the page to the path specified as if it was a normal form post
function postToDotNet(path, params) {
var form = document.createElement("form"),
createFields = function (data, fieldPrefix) {
if (fieldPrefix === undefined) fieldPrefix = '';
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
createFields(data[i], fieldPrefix + '[' + i + ']');
}
} else if (isObject(data) && hasFields(data)) {
for (var key in data) {
createFields(data[key], (fieldPrefix.length ? fieldPrefix + '.' : fieldPrefix) + key);
}
} else {
setField(fieldPrefix, data);
}
},
setField = function (name, value) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", name);
hiddenField.setAttribute("value", value);
form.appendChild(hiddenField);
};
form.setAttribute("method", "post");
form.setAttribute("action", path);
createFields(params);
document.body.appendChild(form);
form.submit();
}
function hasFields(o) {
return Object.keys(o).length > 0;
}
function isObject(o) {
return o === Object(o);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment