Skip to content

Instantly share code, notes, and snippets.

@AuthorProxy
Last active July 3, 2016 12:09
Show Gist options
  • Select an option

  • Save AuthorProxy/76a341c999aee5f2d763 to your computer and use it in GitHub Desktop.

Select an option

Save AuthorProxy/76a341c999aee5f2d763 to your computer and use it in GitHub Desktop.
JSON Array Post methods
// The same but for 'GET'
$.ajax({
url: '/Backend/Article/GetChildArticleIds',
traditional: true,
data: {
filter: '',
fieldId: 1115,
ids: [19975]
}
});
/**
* jQuery toDictionary() plugin
* https://gist.github.com/AuthorProxy/76a341c999aee5f2d763
* http://erraticdev.blogspot.ru/2010/12/sending-complex-json-objects-to-aspnet.html
* usage: $.toDictionary([mandatory]data, [optional]prefix, [optional]includeNulls);
* copyright (c) 2011 Robert Koritnik
*/
(function ($) {
if ($.isFunction(String.prototype.format) === false)
{
String.prototype.format = function () {
var s = this;
var i = arguments.length;
while (i--)
{
s = s.replace(new RegExp("\\{" + i + "\\}", "gim"), arguments[i]);
}
return s;
};
}
if ($.isFunction(Date.prototype.toISOString) === false)
{
Date.prototype.toISOString = function () {
var pad = function (n, places) {
n = n.toString();
for (var i = n.length; i < places; i++)
{
n = "0" + n;
}
return n;
};
var d = this;
return "{0}-{1}-{2}T{3}:{4}:{5}.{6}Z".format(
d.getUTCFullYear(),
pad(d.getUTCMonth() + 1, 2),
pad(d.getUTCDate(), 2),
pad(d.getUTCHours(), 2),
pad(d.getUTCMinutes(), 2),
pad(d.getUTCSeconds(), 2),
pad(d.getUTCMilliseconds(), 3)
);
};
}
var _flatten = function (input, output, prefix, includeNulls) {
if ($.isPlainObject(input))
{
for (var p in input)
{
if (includeNulls === true || typeof (input[p]) !== "undefined" && input[p] !== null)
{
_flatten(input[p], output, prefix.length > 0 ? prefix + "." + p : p, includeNulls);
}
}
}
else
{
if ($.isArray(input))
{
$.each(input, function (index, value) {
_flatten(value, output, "{0}[{1}]".format(prefix, index));
});
return;
}
if (!$.isFunction(input))
{
if (input instanceof Date)
{
output.push({ name: prefix, value: input.toISOString() });
}
else
{
var val = typeof (input);
switch (val)
{
case "boolean":
case "number":
val = input;
break;
case "object":
// this property is null, because non-null objects are evaluated in first if branch
if (includeNulls !== true)
{
return;
}
default:
val = input || "";
}
output.push({ name: prefix, value: val });
}
}
}
};
$.extend({
toDictionary: function (data, prefix, includeNulls) {
/// <summary>Flattens an arbitrary JSON object to a dictionary that Asp.net MVC default model binder understands.</summary>
/// <param name="data" type="Object">Can either be a JSON object or a function that returns one.</data>
/// <param name="prefix" type="String" Optional="true">Provide this parameter when you want the output names to be prefixed by something (ie. when flattening simple values).</param>
/// <param name="includeNulls" type="Boolean" Optional="true">Set this to 'true' when you want null valued properties to be included in result (default is 'false').</param>
// get data first if provided parameter is a function
data = $.isFunction(data) ? data.call() : data;
// is second argument "prefix" or "includeNulls"
if (arguments.length === 2 && typeof (prefix) === "boolean")
{
includeNulls = prefix;
prefix = "";
}
// set "includeNulls" default
includeNulls = typeof (includeNulls) === "boolean" ? includeNulls : false;
var result = [];
_flatten(data, result, prefix || "", includeNulls);
return result;
}
});
})(jQuery);
var ajaxData = [
{ ID: 1, ReviewerID = 1 },
{ ID: 1, ReviewerID = 2 },
{ ID: 1, ReviewerID = 3 },
{ ID: 2, ReviewerID = 4 },
{ ID: 2, ReviewerID = 5 }
];
// if you need to post array of objects
// use customized function toDictionary in short form
$.post(EM.RolesModel.links.updateUserReviewers, $.toDictionary(ajaxData))
// or JSON.stringify in full ajax form
$.ajax({
url: EM.RolesModel.links.updateUserReviewers,
type: 'POST',
dataType: 'json',
data: JSON.stringify(ajaxData),
contentType: 'application/json; charset=utf-8'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment