MVC - Editing a list of objects

后端 未结 2 808
盖世英雄少女心
盖世英雄少女心 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:30

    Kirill's reference to Scott Hanselman's blog entry is correct, but you're reading it too narrowly. In the example shown, he passes the array to the action method, but it could just as easily be contained within the parent model as well. The same concept applies.

    However, one thing to know is that the default model binder does not instantiate nested classes, so it will not create an instance of the List class, which means it will always be null. To fix this, you must instantiate the empty list class in the constructor.

    This is only part of the problem, though as the data must be formatted in the correct way for the model binder to bind it. This is where Scott's blog post comes in, as it provides the format needed for the model binder to recognize the data as a list.

    This is typically handled for you if you use an EditorTemplate and use Html.EditorFor(m => m.Items) and then have a SomeItem.cshtml EditorTemplate. This deals with the issues of collection item naming (so long as you also use strongly typed helpers in the template as well).

提交回复
热议问题