Search code examples
c#jqueryajaxserializationasp.net-mvc-5

Unable to cast object of type Person to type PersonViewModel


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.


Solution

  • It looks like this suffers from the same bug identified in ASP.NET MVC Model Binding with jQuery ajax request

    There is a bug in MVC they refuse to fix that if the colection property name begins with the type name it does not bind.

    Try changing:

    public class PersonViewModel
    {
        public List<Person> Persons {get; set}
    }
    

    To:

    public class PersonViewModel
    {
        public List<Person> People {get; set}
    }
    

    Try this; if you're still having trouble post below and I'll assist.