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
Set the traditional property to true before making the get call. i.e.:
jQuery.ajaxSettings.traditional = true
$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {...
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 }
});
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:
$.param
is for the
traditional
property, which
MUST be true
for this to work. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With