I am trying to send a form array of data my server but it not binding correctly.
public class PersonViewModel
{
public List<Person> Persons {get; set}
}
public class Person{
public string FirstName {get; set;}
}
// view model that wil render all the partial view models showing all the people
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id="people-form" autocomplete = "off" }))
{
<div class="container">
@for (int i = 0; i < Model.Persons.Count; i++)
{
<div>
<label>
@Html.TextBoxFor(x => x.Persons[i].FirstName)
</label>
</div>
}
</div>
}
// ajax used to post, trying to serialize it as an array but still when it hits my action it is not binding.
return $.ajax({
method: 'POST',
url: 'SavePeople',
data: $('#people-form').serializeArray(),
}).done(function (response) {
}).fail(function (err) {
});
[HttpPost]
public JsonResult SavePeople(PersonViewModel vm /* this comes in as null */)
{
}
The data getting sent looks like Persons[0].FirstName: 41441
but for some reason it is trying to bind it directly into the PersonViewModel instead of adding it to the Persons Collection.
3
Answers
It looks like this suffers from the same bug identified in ASP.NET MVC Model Binding with jQuery ajax request
Try changing:
To:
Try this; if you’re still having trouble post below and I’ll assist.
First of all, please make sure your ajax is working.
Variable References to your project
Once, your ajax function is able to execute, you can directly access the value in your SavePeople action, using
vm.Persons
– which is a List.assuming that you haven’t customized serialization settings and model is
@model HomeController.PersonViewModel
. The following expresssion worksif nothing works just use IFormCollection and parse values manually or for debugging the specific issue in Model Binding.