Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting a JavaScript Array with jQuery Post to a ASP.NET MVC Action taking a IEnumerable<T> [duplicate]

Consider that I have the following javascript that do a post:

$.post("/MyController/SomeAction", 
      { myParam: ['Filip', 'Ekberg'] }, function(data) { alert(data); }, "html");

My Action looks like this:

[HttpPost]
public ActionResult SomeAction(FormCollection collection, 
                               IEnumerable<string> myParam)
{
    return null;
}

When I enter this Action, myParam is null, if I expand the FormCollection I see this:

enter image description here

The weird part here is that the name ( Key ) is myParam[] which might be why it is not mapped to myParam.

Also, I tried doing dynamic[] myParam as well, but it doesn't work either.

I know that I can use JSON.stringify but I don't want to do that now. So, any ideas what's going on here and if there is a solution?

like image 962
Filip Ekberg Avatar asked Dec 30 '25 13:12

Filip Ekberg


1 Answers

Try setting the traditional parameter to true:

$.ajax({
    url: '/MyController/SomeAction',
    type: 'POST',
    data: { myParam: [ 'Filip', 'Ekberg' ] },
    traditional: true,
    success: function(data) {
        alert(data);
    }
});

Also you can safely remove the FormCollection parameter from your POST action signature. It's useless.

like image 62
Darin Dimitrov Avatar answered Jan 02 '26 03:01

Darin Dimitrov