2014-12-07 59 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