Model Binding to a List MVC 4 | mvc list
ThisishowIdoitifIneedaformdisplayedforeachitem,andinputsforvariousproperties.ReallydependsonwhatImtryingtodothough.ViewModellookslikethis:publicclassMyViewModel{publicList
This is how I do it if I need a form displayed for each item, and inputs for various properties. Really depends on what Im trying to do though.
ViewModel looks like this:
public class MyViewModel { public List<Person> Persons{get;set;} }View(with BeginForm of course):
@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:
[HttpPost]public ViewResult(MyViewModel vm) { ...Note that on post back only properties which had inputs available will have values. I.e., if Person had a .SSN property, it would not be available in the post action because it wasnt a field in the form.
Note that the way MVCs model binding works, it will only look for consecutive IDs. So doing something like this where you conditionally hide an item will cause it to...