JS int array to MVC3 controller JS int array to MVC3 controller arrays arrays

JS int array to MVC3 controller


Have you tried not stringifying the array and letting mvc's default model binding do the magic

$.ajax({url: someUrl, data: {ids : id_array }, ...)

I'm pretty sure .net MVC will see the array and see it is an array of ints and map it to your array of ints correctly


For MVC3 you need to configure jQuery to use traditional, "shallow" serialisation.. See here.

Client-side AJAX request:

jQuery.ajaxSettings.traditional = true; //enable "shallow" serialisation globally$.get("someUrl", {ids : id_array });

Action Method:

public ActionResult MyAction(string[] ids) { ... }


You can do this in two different ways

1. Use $.ajax to post data to your action

$.ajax({    url: '/myController/myAction',    dataType: 'json',    type: 'POST',    contentType: 'application/json; charset=utf-8',    traditional: true,    data: $.toJSON(json),    success: function (data, textStatus, jqXHR) {    ...    }});

Your action should look like this one

public class myController{    [HttpPost]    public ActionResult myAction(List<int> json)    {        ....    }}

2. Use $.post to post your data

$.post(    '/myController/myAction',    { json: $.toJSON(products) },    function (data) {    ...});

In your action you should deserialize JSON string

public class myController    {    public ActionResult myAction(string json)    {        JavaScriptSerializer serializer = new JavaScriptSerializer();        List<int> list = serializer.Deserialize<List<int>>(json);    }}

You need to download and include jquery.json-2.2.min.js to your code.

http://code.google.com/p/jquery-json/downloads/detail?name=jquery.json-2.2.min.js