在MVC中向EditorFor添加类

ar.*_*gin 4 css asp.net-mvc asp.net-mvc-4

我想Enum在EditorFor中展示.我使用编辑模板来显示它.(DropDownList).

我看到了麦芽EditorFor.我想为某些控件设置类.

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

在编辑器中:Views/Shared/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)
Run Code Online (Sandbox Code Playgroud)

在模型中

[DisplayName("??? ???")]
[UIHint("Enum")]
public DocumentType DocumentType { get; set; }
Run Code Online (Sandbox Code Playgroud)

小智 6

您可以将类名传递给EditorTemplateusing AdditionalViewData.

在主视图中

@Html.EditorFor(m => m.DocumentType, new { htmlAttributes = new { @class = "myclass" } })
Run Code Online (Sandbox Code Playgroud)

并在 EditorTemplate

....
@Html.DropDownListFor(m => m, values, ViewData["htmlAttributes"])
Run Code Online (Sandbox Code Playgroud)

然而,包括SelectList在一个的逻辑EditorTemplate是不好的做法.我建议你考虑创建一个扩展方法来生成SelectList,然后这EditorTemplate不是必需的.请参阅此示例.并且Selected = v.Equals(Model),没有意义,因为Selected属性将被忽略(所选项目将是值DocumentType)