1

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?

2
  • try JSON.stringify({person:[....]}) in $.post() Commented Oct 11, 2012 at 19:53
  • @prashanth Doing this person is null. Commented Oct 11, 2012 at 19:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.