モデルの一覧データのバインド
モデルの内部にある一覧を画面とモデルでバインドする方法
ViewModel
public class MyViewModel { public Parent parent { get; set; }; public List<Child> childlist {get; set;} } public class Parent { public string Name { get; set; } } public class Child { public string ParentName { get; set; } public string Name { get; set; } }
Controller
public ActionResult Update(MyViewModel model) { foreach (var item in from m in model.child{ // 画面で設定された内容にアクセス出来る。 } }
View.cshtml
@@using (Html.BeginForm("Update", "Home", FormMethod.Post)) { <table> <tr> <th>ParentName</th> <th>ChildName</th> </tr> </table> @for (int i=0; i < Model.childlist.Count; i++) { <tr> <td >@Html.EditorFor(modelItem => Model.childlist[i].ParentName)</td> <td >@Html.EditorFor(modelItem => Model.childlist[i].Name)</td> </tr> } }
実際生成されるhtml
<tr> <td> <input class="text-box single-line" id= "childlist_0____" name= "childlist[0].ParentName" type= "text" value= "Jone" </td> <td> <input class="text-box single-line" id= "childlist_0____" name= "childlist[0].Name" type= "text" value= "Jone Jr" /> </td> </tr> <tr> <td> <input class="text-box single-line" id= "childlist_1____" name= "childlist[1].ParentName" type= "text" value= "Jone" </td> <td> <input class="text-box single-line" id= "childlist_1____" name= "childlist[1].Name" type= "text" value= "harry" /> </td> </tr>