user895400
user895400

Reputation: 368

ASP.NET Mvc 3 Model binding to a collection not working

I am trying to create an edit form for a collection of items. The List is null and when I check the ModelState its Valid property is "true" and it has 0 keys. There are no required properties on the People entity.

View

@using(Html.BeginForm("UpdatePeople", "People", FormMethod.Post }))
{
    @for (var i = 0; i < Model.People.Count; i++)
    {
        <div>


 @Html.TextBoxFor(t => t.People[i].FirstName)



       </div>
     }
}   

Controller

[HttpPost]
public ActionResult UpdatePeople(List<People> items)
{                    
 // items is null
}

Upvotes: 0

Views: 1647

Answers (1)

dknaack
dknaack

Reputation: 60556

Your Action Method receives not the model of type List<People> it receives your ViewModel.

I don't see your model definition, so a little sample.

It look like that you have a Model which has a property named People of type List<People>.

public class MyViewModel
{
    public List<People> People { get; set; }
    // other properties
}

If you now submit your Form, MVC try to Bind it. Your action method said it receives a

List<People>

but your send MyViewModel.

So if you change your action method to

[HttpPost]
public ActionResult UpdatePeople(MyViewModel model)
{                    
    // model.People exists

}

it will work.

If your ViewModel has only the one propertie People you don't need this model. You can pass List<Person> to your view.

hope this helps

Upvotes: 1

Related Questions