Pass array to mvc Action via AJAX
I'm trying to pass an array (or IEnumerable) of ints from via AJAX to an MVC action and I need a little help.
the javascript is
$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {...
and the controller action is
public ActionResult MyAction(IEnumerable<int> arrayOfValues )
At the moment the request is formatted as
controller/MyAction?_=1301503418429&arrayOfValues[]=491&arrayOfValues[]=368&arrayOfValues[]=235&arrayOfValues[]=437
So I'm almost there, if I take the square brackets off I get the correct response. How should I be passing that array into my get so that the controller can recognise what it is?
Many thanks for your help
Dave
Solution 1:
Set the traditional property to true before making the get call. i.e.:
jQuery.ajaxSettings.traditional = true
$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {...
Solution 2:
I have had issues in the past when attempting to perform a POST (not sure if that is exactly what you are doing, but I recall when passing an array in, traditional must be set to true.
var arrayOfValues = new Array();
//Populate arrayOfValues
$.ajax({
type: "POST",
url: "<%= Url.Action("MyAction","Controller")%>",
traditional: true,
data: { 'arrayOfValues': arrayOfValues }
});
Solution 3:
Quite a late, but different answer to the ones already present here:
If instead of $.ajax
you'd like to use shorthand functions $.get
or $.post
, you can pass arrays this way:
Shorthand GET
var array = [1, 2, 3, 4, 5];
$.get('/controller/MyAction', $.param({ data: array }, true), function(data) {});
// Action Method
public void MyAction(List<int> data)
{
// do stuff here
}
Shorthand POST
var array = [1, 2, 3, 4, 5];
$.post('/controller/MyAction', $.param({ data: array }, true), function(data) {});
// Action Method
[HttpPost]
public void MyAction(List<int> data)
{
// do stuff here
}
Notes:
- The boolean parameter in
$.param
is for thetraditional
property, which MUST betrue
for this to work.
Solution 4:
You should be able to do this just fine:
$.ajax({
url: 'controller/myaction',
data: JSON.stringify({
myKey: myArray
}),
success: function(data) { /* Whatever */ }
});
Then your action method would be like so:
public ActionResult(List<int> myKey)
{
// Do Stuff
}
For you, it looks like you just need to stringify your values. The JSONValueProvider in MVC will convert that back into an IEnumerable for you.
Solution 5:
The answer to use the 'traditional' option is correct. I'm just providing some more background info for this who wish to learn more.
From the jQuery documentation:
As of jQuery 1.8, the $.param() method no longer uses jQuery.ajaxSettings.traditional as its default setting and will default to false.
You can also read more here: http://michaelsync.net/2012/04/05/tips-asp-net-mvc-javascriptserializer-3-questions-and-3-answers and http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
HTH