How to send collection / array to mvc action via ajax

atm I try so hard, but no luck, I got a null value in the Do action.

var arr = [31,17,16]; $.get('<%=Url.Action("Do", "Foo") %>', {ids:arr}, function(d){...}); public ActionResult Do(IEnumerable<int> ids) { ... } 
+6
jquery ajax asp.net-mvc
source share
2 answers

Try it like this:

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

Pay attention to 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) { } ); 
+6
source share

I just stumbled upon this problem, but instead found an alternative solution. I prefer this over traditional , so I will post it here so that 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 type of data I sent, regardless of complexity. This is actually completed in a class called RequestService , which does this for all requests from our client script in the MVC API Controller. There are many other nice attributes for this object, such as timeout or headers . Check out the full document here .

I am running the .NET Framework 4.5 and JQuery 1.7.1, although I believe this version of $.ajax from 1.5

+2
source share

All Articles