Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

3 Answers

up vote 42 down vote accepted

Set the traditional property to true before making the get call. i.e.:

jQuery.ajaxSettings.traditional = true

$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {... 
share|improve this answer
thank you! could you please outline the differences between traditional and non traditional ajax? i'd like to better understand what i'm doing to the rest of my application. – Tom Beech Jan 15 at 16:19
you can also add the traditional setting to a single call. Then it will not affect the rest – Gluip Apr 28 at 10:11

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.

share|improve this answer
Thanks for the answer but I think it looks like I need to set traditional to true. Have upvoted as I think this would work too. – Dave Mar 30 '11 at 17:06

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")%>",
      datatype: "json",
      traditional: true,
      data: { 'arrayOfValues': arrayOfValues }              
 });
share|improve this answer
Thanks - THis is correct I need to set traditional to true. Have upvoted as well – Dave Mar 30 '11 at 17:07
No problem - glad it helped! – Rion Williams Mar 30 '11 at 17:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.