Binding an IList to a view in MVC 4 can be achieved through the following steps:
Define a ViewModel with a List property:
public class MyViewModel { public List<Person> Persons{get;set;} }
In the View, create a form and iterate through the list to render input fields:
@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) }
In the Action, receive the posted ViewModel:
[HttpPost]public ViewResult(MyViewModel vm) { ... }
Note that only properties with inputs in the form will be populated in the postback. If properties are conditionally hidden, gaps in the ID sequence will cause binding issues for subsequent items.
The above is the detailed content of How to Bind an IList to a View in MVC 4?. For more information, please follow other related articles on the PHP Chinese website!