2011-10-03 85 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',但似乎沒有工作:( –

相關問題