MVC - Editing a list of objects

后端 未结 2 819
盖世英雄少女心
盖世英雄少女心 2020-12-10 13:51

I have the following class layout in MVC:

public class ReportModel 
{
    List items;
    string value;
    string anotherValue;
}

2条回答
  •  星月不相逢
    2020-12-10 14:37

    Don't use ElementAt(1) in your lambda expressions => this ruins your input field names. Please read the blog post that Kirill suggested you.

    So you could use indexed access:

    for (int i = 0; i < Model.items.Count; i++)
    {                
        
    @Html.LabelFor(m => m.items[i].propertyOne)
    @Html.TextBoxFor(m => m.items[i].propertyOne) @Html.ValidationMessageFor(m => m.items[i].propertyOne)
    @Html.LabelFor(m => m.items[i].propertyTwo)
    @Html.TextBoxFor(m => m.items[i].propertyTwo) @Html.ValidationMessageFor(m => m.items[i].propertyTwo)
    @Html.LabelFor(m => m.items[i].propertyThree)
    @Html.TextBoxFor(m => m.items[i].propertyThree) @Html.ValidationMessageFor(m => m.items[i].propertyThree)
    }

    Of course in order to have indexer access to the collection this assumes that your items property is declared as either List or SomeItem[]. If it is an IEnumerable it won't work. So simply change the type of this property on your view model.

提交回复
热议问题