2014-12-07 58 views
1

我想在EditorFor中顯示Enum。我使用編輯器模板來顯示它(DropDownList)。將類添加到MVC中的EditorFor

我有麥芽EditorFor的意見。我想爲某些控件設置類。

@Html.EditorFor(m => m.Position, new { @class = "smallinput", style = "width:150px !important" }) 
@Html.EditorFor(m => m.DocumentType) 

在編輯:查看/共享/ DisplayTemplates/Enum.cshtml

@model Enum 
@{ 
    var values = Enum.GetValues(ViewData.ModelMetadata.ModelType).Cast<object>() 
       .Select(v => new SelectListItem 
       { 
        Selected = v.Equals(Model), 
        Text = v.GetDisplayName(), 
        Value = v.ToString() 
       }); 
} 
@Html.DropDownList("", values) 

在型號

[DisplayName("نوع سند")] 
[UIHint("Enum")] 
public DocumentType DocumentType { get; set; } 
+0

您需要MVC 5使用具有html屬性的'@ Html.EditorFor()'。對於MVC 4,您需要使用'@ Html.TextBoxFor()'或類似的。另一種選擇是傳遞HTML屬性作爲'AdditionalViewData'並使用自定義'EditorTemplate' – 2014-12-07 08:46:36

+0

謝謝,我想在下拉菜單中顯示枚舉,所以我使用EditorFor.I使用MVC4。我可以使用'AdditionalViewData'作爲傳遞類來編輯器? – 2014-12-07 08:56:22

+0

你需要包括'EditorTemplate'你用來渲染下拉 – 2014-12-07 08:57:30

回答

2

您可以通過使用AdditionalViewData類名到EditorTemplate

在主視圖中

@Html.EditorFor(m => m.DocumentType, new { htmlAttributes = new { @class = "myclass" } }) 

並在EditorTemplate

.... 
@Html.DropDownListFor(m => m, values, ViewData["htmlAttributes"]) 

但是包括一個用於在所述EditorTemplateSelectList邏輯不是好的做法。我會建議你考慮創建一個生成SelectList的擴展方法,然後這個EditorTemplate將不需要。 Refer this example。並且Selected = v.Equals(Model),是沒有意義的,因爲Selected屬性將被忽略(所選項目將是值DocumentType

+0

非常感謝:) – 2014-12-07 09:43:03