MuriloKunze
MuriloKunze

Reputation: 15583

$.post array of data

I'm trying to post some array of data to controller.. My view is like:

<script>
   $.post("/",{
       person: [
           { id: 1, name: "a" },
           { id: 2, name: "b" }
       ]
   });
</script>

and in my controller:

[HttpPost]
public ActionResult Index(List<Person> person)
{
    //something
}

When I inspect the sent http data, I see that data is:

person[0][id]
person[0][name]
person[1][id]
person[1][name]

but the correct for default model binder is:

person[0].id
person[0].name
person[1].id
person[1].name

How can I fix it?

Upvotes: 1

Views: 81

Answers (1)

nemesv
nemesv

Reputation: 139758

You cannot do it with $.post you need use $.ajax because you need to set the contentType to 'application/json' to make the mobel binder happy what you cannot do with $.post

$.ajax({
        url: '/',
        type: 'POST',
        data: JSON.stringify({
            person: [
                { id: 1, name: "a" },
                { id: 2, name: "b" }
            ]
        }),
        contentType: 'application/json'
    });

And you also need to JSON.stringify your data to make it work with the modelbinder.

Upvotes: 1

Related Questions