2

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?

Community
  • 1
  • 1
Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183

2 Answers2

6

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks Darin, worked perfectly. It's a bit weird behaviour though, why isn't the paramemter-binder smart enough to fix that? Anyways, thanks! `FormCollection` was just there to debug it all. – Filip Ekberg Oct 31 '11 at 08:30
  • 1
    @FilipEkberg, the default model binder follows strict rules for binding collections: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx The fact that you are not obeying those rules when sending the request is not a reason to blame the model binder for. The thing is that the jQuery team changed the way parameters are serialized in v1.4 and broke compatibility. That's why they introduced the `traditional` parameter. – Darin Dimitrov Oct 31 '11 at 08:32
4

If you use $.ajax instead of $.post, you can set traditional to true, which should generate the correct name (myParam instead of myParam[]).

The the article about $.param() for information why.

Michael Stum
  • 177,530
  • 117
  • 400
  • 535