EditorFor()复杂类型的列表(MVC) [英] EditorFor() for a List of Complex Type (MVC)

查看:385
本文介绍了EditorFor()复杂类型的列表(MVC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个复杂类型的列表创建EditorFor()。特别是在选项下面应该得到显示在一个multitext输入其中每个选项(串)是一个新行。但是,我只能显示一个文本框,一个选项,而不是所有的选项....

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....

我的视图模型和Class:

My View Model and Class:

public class ItemViewModel
{
    public int itemId { get; set; }

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

我的编辑模板:

EditorTemplates \\ Item.cshtml

EditorTemplates\Item.cshtml

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

EditorTemplates \\ Option.cshtml

EditorTemplates\Option.cshtml

//Not sure how to dispay the options here
<textarea rows="4" cols="50">
Display Options
</textarea>

如果更新我的EditorTemplates为:

If I update my EditorTemplates to:

EditorTemplates \\ Item.cshtml

EditorTemplates\Item.cshtml

@model ItemViewModel
@Html.EditorFor(model => model.Options[0])

EditorTemplates \\ Option.cshtml

EditorTemplates\Option.cshtml

@Html.TextBoxFor(x => x.OptionText)

它会显示一个文本框的第一个选项。但是,再我想要做到的,是在multitext输入到显示所有选项。

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.

任何想法?

推荐答案

您几乎拥有它。

在此 EditorTemplates \\ Option.cshtml 添加以下内容:

@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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆