Post Form MVC with List of List

前端 未结 1 1419
感情败类
感情败类 2020-12-19 14:04

Most of the Tutorials, Questions I found online where about when the Model has one List of Items. But In my Case I have a List of Items which further have a List of Items.

1条回答
  •  心在旅途
    2020-12-19 14:38

    Its fairly simple - you just need to nest 2 for loops in the view (don't use foreach)

    ie change to:

    @Html.BeginForm(){
    
    @for(int j = 0; j < Model.Items.Count; j++)
    {
        

    @Model.Items[j].ItemAId

    @Html.HiddenFor(m => m.Items[j].ItemAId) @* (don't forget this!) *@ for (int i = 0; i < Model.Items[j].ItemBList.Count; i++) { @Html.HiddenFor(m => m.Items[j].ItemBList[i].ItemBId ) @Html.TextBoxFor(m => m.Items[j].ItemBList[i].NewInput) } } }

    The MVC Model Binder requires form fields representing properties in lists to be named something like [#].property1name, [#].property2name in order to properly associate them to each other during binding after postback. Same principle applies to list properties of listitems. You need to use a for loop rather than a foreach loop to get the right form field names when using HTML helpers!

    0 讨论(0)
提交回复
热议问题