Last active
October 5, 2016 20:30
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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