Omu
Omu

Reputation: 71288

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)
{
...
}

Upvotes: 7

Views: 4246

Answers (2)

Nick
Nick

Reputation: 9154

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

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

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) {

    }
);

Upvotes: 6

Related Questions