我正在尝试为复杂类型的列表创建一个EditorFor().具体来说,下面的"选项"应显示在一个多文本输入中,其中每个选项(字符串)都在一个新行中.但是,我只能在文本框中显示一个选项而不是所有选项....
我的视图模型和类:
public class ItemViewModel { public int itemId { get; set; } [UIHint("Option")] public List
我的编辑模板:
EditorTemplates\Item.cshtml
@model ItemViewModel @Html.EditorFor(model => model.Options)
EditorTemplates\Option.cshtml
//Not sure how to dispay the options here
如果我将EditorTemplates更新为:
EditorTemplates\Item.cshtml
@model ItemViewModel @Html.EditorFor(model => model.Options[0])
EditorTemplates\Option.cshtml
@Html.TextBoxFor(x => x.OptionText)
它将显示文本框中的第一个选项.但是,我想要实现的是在多文本输入中显示所有选项.
有任何想法吗?
只需创建一个视图 Shared/EditorTemplates/Option.cshtml
@model Option @Html.TextBoxFor(m => m.Text)
并致电
@Html.EditorFor(model => model.Options)
EditorFor为您迭代集合.
你几乎拥有它.
在此EditorTemplates\Option.cshtml
添加以下内容:
@model IEnumerable<Option> @foreach(var option in Model) { @Html.TextBoxFor(m => option.Text) }
然后在你的视图中调用它,如下所示:
@Html.EditorFor(model => model.Options)
如果您没有在初始get中填充选项,则需要在ItemViewModel类中添加它:
public class ItemViewModel { public ItemViewModel() { Options = new List<Option>(); } public int itemId { get; set; } [UIHint("Option")] public List<Option> Options { get; set; } }
此构造函数初始化集合:
public ItemViewModel() { Options = new List<Options>(); }