Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send a collection/array to mvc action via ajax

atm I'm trying like this, but no luck, I get null in my Do action

var arr = [31,17,16];

$.get('<%=Url.Action("Do", "Foo") %>', 
       {ids:arr},
       function(d){...});

public ActionResult Do(IEnumerable<int> ids)
{
...
}
like image 860
Omu Avatar asked Dec 21 '10 13:12

Omu


2 Answers

Try like this:

$.ajax({
    url: '<%= Url.Action("Do", "Foo") %>',
    data: { ids: [ 31, 17, 16] },
    traditional: true,
    success: function(result) {

    }
});

Notice the traditional: true parameter.

Or if you insist on the $.get() function:

$.get(
    '<%= Url.Action("Do", "Foo") %>', 
    $.param({ ids: [31, 17, 16] }, true), 
    function (result) {

    }
);
like image 73
Darin Dimitrov Avatar answered Nov 15 '22 10:11

Darin Dimitrov


I just stumbled upon this problem, but found an alternative solution instead. I prefer this over traditional, so I'll post it here so others can choose for themselves.

$.ajax(url, 
    {
        type: method,                    //"GET", or "POST", etc. The REST verb
        data: JSON.stringify(myData),    //stringify your collection or complex object
        contentType:"application/json",  //tell the controller what to expect
        complete: callback
    });
});

This works for every data type I've sent, no matter how complex. We actually have this wrapped in a class called RequestService which does this for all requests from our client script to the MVC API Controller. There are plenty of other nice attributes to give this object, like timeout, or headers. Check out the full docs here.

I'm running .NET Framework 4.5, and JQuery 1.7.1, though I believe this version of $.ajax is since 1.5

like image 24
Nick Avatar answered Nov 15 '22 08:11

Nick