2011-10-03 92 views
4

我试图在Create视图中显示类对象,其中属性为ICollection<string>试图在ASP.NET MVC3视图中使用EditorFor与ICollection <string>?

例如...

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,但没有在浏览器中显示,因为它不知道如何渲染字符串集合。

回答

6

开始通过与[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)) 

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

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

不应该是'〜/ Views/Shared/EditorTemplates/tags.cshtml'吗? –

+0

@MystereMan,是的,它应该。感谢您的注意。 –

+1

如何在收回数据时保留收集数据?我试着用'HiddenFor'在编辑器模板中添加一个'foreach',但似乎没有工作:( –

相关问题