【问题标题】:Trying to use EditorFor with an ICollection<string> in an ASP.NET MVC3 View?试图在 ASP.NET MVC3 视图中将 EditorFor 与 ICollection<string> 一起使用?
【发布时间】:2011-10-05 00:35:09
【问题描述】:

我正在尝试在Create 视图中显示一个类对象,其中属性是ICollection&lt;string&gt;

例如...

namespace StackOverflow.Entities
{
    public class Question
    {
        public int Id { get; set; }
        ....
        public ICollection<string> Tags { get; set; }
    }
}

如果视图类似于 StackOverflow 的“提问”页面,其中 Tags html 元素是单个 input box .. 我不确定如何在 ASP.NET MVC3 视图中做到这一点?

有什么想法吗?

我尝试使用EditorFor,但浏览器中没有显示任何内容,因为它不确定如何呈现字符串集合。

【问题讨论】:

    标签: c# .net asp.net-mvc-3 editorfor


    【解决方案1】:

    首先使用[UIHint] 属性装饰您的视图模型:

    public class Question
    {
        public int Id { get; set; }
    
        [UIHint("tags")]
        public ICollection<string> Tags { get; set; }
    }
    

    然后在主视图中:

    @model StackOverflow.Entities.Question
    @Html.EditorFor(x => x.Tags)
    

    然后您可以编写自定义编辑器模板 (~/Views/Shared/EditorTemplates/tags.cshtml):

    @model ICollection<string>
    @Html.TextBox("", string.Join(",", Model))
    

    或者如果你不喜欢装饰,你也可以直接在视图中指定用于给定属性的编辑器模板:

    @model StackOverflow.Entities.Question
    @Html.EditorFor(x => x.Tags, "tags")
    

    【讨论】:

    • 不应该是~/Views/Shared/EditorTemplates/tags.cshtml吗?
    • @MystereMan,是的,应该。感谢您的关注。
    • 收集数据回发时如何保留?我尝试使用HiddenFors 在我的编辑器模板中添加foreach,但似乎没有用:(
    猜你喜欢
    • 2016-01-19
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    相关资源
    最近更新 更多