EditorFor() for a List of Complex Type (MVC)

眉间皱痕 提交于 2019-11-27 13:18:29

You nearly have it.

In this EditorTemplates\Option.cshtml add the following:

@model IEnumerable<Option>
@foreach(var option in Model)
{
   @Html.TextBoxFor(m => option.Text)
}

Then call it in your view like this:

@Html.EditorFor(model => model.Options)

If you are not populating your options on the initial get, you will need to add this in your ItemViewModel class:

public class ItemViewModel
{
    public ItemViewModel()
    {
        Options = new List<Option>();
    }
    public int itemId { get; set; }

    [UIHint("Option")]
    public List<Option> Options { get; set; }
}

This constructor initializes the collection:

public ItemViewModel()
{
    Options = new List<Options>();
}

Just create a view in Shared/EditorTemplates/Option.cshtml

@model Option

@Html.TextBoxFor(m => m.Text)

And call

@Html.EditorFor(model => model.Options)

EditorFor iterates over collection for you.

I bumped into the same issue and I have different solution but a bit similar with hutchonoid.

So the first part is same, modify the Option.cshtml like following:

@model IEnumerable<Option>
@foreach(var option in Model)
{
   @Html.TextBoxFor(m => option.Text)
}

And in Item.cshtml, I call the Option.cshtml using Html.Partial, like following:

@Html.Partial("Option", model:Model.Options)

And in my case, I don't have to modify the ItemViewModel class. Hopefully this can be alternative answer for this problem. Cheers!

Willy

Using @hutchonoid's answer, you should call the template in view:

@Html.EditorFor(model => Model.Options)

instead of

@Html.EditorFor(model => model.Options)

and please be noted, the Option.cshtml template is in Views\Item\EditorTemplates\Option.cshtml or View\Shared\EditorTemplates\Option.cshtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!