Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS int array to MVC3 controller

I've got an array of strings in JS. All the members are actually numbers.
My controller has an int[] parameter.

I send it from jquery:

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

and I receive it using

public ActionResult MyAction(int[] ids) { ...

The parameter doesn't get filled, I've checked, the Request.Form["ids"] contains "[\"25\",\"26\"]", the string represention of the JSON array. Is there any way to do this automatically without a lot of int parsing?

like image 776
TDaver Avatar asked Nov 26 '11 20:11

TDaver


3 Answers

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

like image 110
Keith.Abramo Avatar answered Nov 08 '22 18:11

Keith.Abramo


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) { ... }
like image 36
Lloyd Avatar answered Nov 08 '22 16:11

Lloyd


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

like image 21
adyusuf Avatar answered Nov 08 '22 18:11

adyusuf