问题描述
我正在尝试为复杂类型的列表创建一个 EditorFor().具体来说,下面的选项"应该显示在一个多文本输入中,其中每个选项(字符串)都在一个新行中.但是,我只能在文本框中显示一个选项,而不是所有选项....
I'm trying to create an EditorFor() for a List of a Complex Type. Specifically the "Options" below should get displayed in a one multitext input where each option(string) is in a new line. However, I can only display one option in a textbox and not all options....
我的视图模型和类:
public class ItemViewModel
{
public int itemId { get; set; }
[UIHint("Option")]
public List<Option> Options { get; set; }
}
public class Option
{
public string Text { get; set; }
}
我的编辑器模板:
EditorTemplatesItem.cshtml
EditorTemplatesItem.cshtml
@model ItemViewModel
@Html.EditorFor(model => model.Options)
EditorTemplatesOption.cshtml
EditorTemplatesOption.cshtml
//Not sure how to dispay the options here
<textarea rows="4" cols="50">
Display Options
</textarea>
如果我将 EditorTemplates 更新为:
If I update my EditorTemplates to:
EditorTemplatesItem.cshtml
EditorTemplatesItem.cshtml
@model ItemViewModel
@Html.EditorFor(model => model.Options[0])
EditorTemplatesOption.cshtml
EditorTemplatesOption.cshtml
@Html.TextBoxFor(x => x.OptionText)
它将在文本框中显示第一个选项.但是,我再次尝试实现的是在多文本输入中显示所有选项.
It will display the first option in a textbox. But, again what I'm trying to achieve is to display all options in a multitext input.
有什么想法吗?
推荐答案
您几乎拥有它.
在此 EditorTemplatesOption.cshtml
中添加以下内容:
In this EditorTemplatesOption.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)
如果您没有在初始获取时填充您的选项,则需要将其添加到您的 ItemViewModel 类中:
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>();
}
这篇关于EditorFor() 用于复杂类型列表 (MVC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!