自定义`EditorFor`助手创建的每个元素

时间:2017-11-14 02:27:07

标签: asp.net-mvc asp.net-core-mvc html-helper

EditorFor帮助器可用于自动搭建模型(如果用作EditorFor(x=> x, new {htmlAttributes = new {@class = "x"}}))。问题是,由于它自动生成标签,字段和验证消息,无论如何都要为传递给此方法的匿名类型(new { htmlAttributes = ..})自定义这些元素中的每一个的样式和类?

1 个答案:

答案 0 :(得分:1)

您必须使用EditorTemplateEditorFor帮助程序会根据您的模板自动呈现您的模型,您无需依赖htmlAttributes属性来自定义您的视图。这样做的好处是,如果适用于DateTimeIFormFile等类型,您的模板可以反复使用。您可以参考以下示例:

UserModelTemplate.cshtml:
-------------------------
@model UserModel 

<div class="form-group">
    <label class="hero-label">
         @Html.DisplayNameFor(m=> m.Username)
         <span class="text-danger">
            @Html.ValidationMessageFor(m=> m.Username)
         </span>
     </label>
     @Html.TextBoxFor(m=> m.Username, new { @class = "form-control"})
</div>

你可以继续这样做。完成模板开发后,您可以将其与EditorFor帮助程序一起使用(将其放在共享文件夹中,也可以放在子文件夹中以便更好地进行组织

@Html.EditorFor(model=> model, "UserModelTemplate")