【问题标题】:Adding class to EditorFor in MVC在 MVC 中向 EditorFor 添加类
【发布时间】:2015-02-05 02:34:26
【问题描述】:

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

我看到了麦芽味EditorFor。我想为一些控件设置类。

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

在编辑器中: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)

在模型中

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

【问题讨论】:

  • 您需要 MVC 5 才能将 @Html.EditorFor() 与 html 属性一起使用。对于 MVC 4,您将需要使用 @Html.TextBoxFor() 或类似名称。另一种选择是将html属性作为AdditionalViewData传递并使用自定义EditorTemplate
  • 谢谢,我想在下拉列表中显示枚举,所以我使用 EditorFor。我使用 MVC4。我可以使用AdditionalViewData 将课程传递给编辑器吗?
  • 您需要包含用于呈现下拉菜单的EditorTemplate
  • 我有一个 EditorTemplate 和渲染下拉菜单,但是如何将类传递给 EditorTemplate?
  • @StephenMuecke - 实际上,html 属性需要 MVC 5.1,这不在 5.0 中。

标签: css asp.net-mvc asp.net-mvc-4


【解决方案1】:

您可以使用AdditionalViewData 将类名传递给EditorTemplate

在主视图中

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

EditorTemplate

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

但是,在 EditorTemplate 中包含 SelectList 的逻辑并不是一个好的做法。我建议您考虑创建一个扩展方法来生成SelectList,然后不需要这个EditorTemplateRefer this example。而Selected = v.Equals(Model), 毫无意义,因为Selected 属性将被忽略(选中的项目将是DocumentType 的值)

【讨论】:

    猜你喜欢
    • 2011-03-26
    • 2017-06-09
    • 1970-01-01
    • 2011-09-11
    • 2016-10-11
    • 1970-01-01
    • 2013-12-23
    • 2012-04-02
    相关资源
    最近更新 更多