MVC 3 json post array workaround

Ajax-posting a JSON object containing arrays using jQuery work fine in PHP, but since ASP.NET expects the array to be posted with indeces a tiny workaround is required. Consider the following example:

var jsonData = { foo: 0, bar: [1, 2] };
$.post("/post-url", postData, function () {});

This will cause the post data to look like

foo=0
bar[]=1
bar[]=2

PHP acceps this, but ASP.NET requires the post data to be

foo=0
bar[0]=1
bar[1]=2

Here’s a workaround. Run it before $.post.

for (property in postData) {
  if (typeof postData[property] == "object" && postData[property] != null) {
    var tmp = postData[property];
    postData[property] = {};
    for (var i = 0; i < tmp.length; i++) {
      postData[property][i] = tmp[i];
    }
  }
}

Add a comment