Model Binding to a List in MVC 4
When attempting to bind an IList of items to a view in MVC 4, issues can arise during HttpPost. To address this challenge, consider the following pattern:
ViewModel:
Create a ViewModel that contains the IList of items:
public class MyViewModel { public List<Person> Persons{get;set;} }
View:
In the view, iterate over the IList and generate form inputs for each property:
@model MyViewModel @for( int i = 0; i < Model.Persons.Count(); ++i) { @Html.HiddenFor(m => m.Persons[i].PersonId) @Html.EditorFor(m => m.Persons[i].FirstName) @Html.EditorFor(m => m.Persons[i].LastName) }
Action:
In the action method, handle the posted MyViewModel object:
[HttpPost]public ViewResult(MyViewModel vm) { ... }
Considerations:
@for( int i = 0; i < Model.Persons.Count(); ++i) { @Html.Hidden($"Persons[{i}].PersonId", Model.Persons[i].PersonId) @Html.Editor($"Persons[{i}].FirstName", Model.Persons[i].FirstName) @Html.Editor($"Persons[{i}].LastName", Model.Persons[i].LastName) }
The above is the detailed content of How Can I Effectively Bind a List to a View in ASP.NET MVC 4 During HttpPost?. For more information, please follow other related articles on the PHP Chinese website!