【问题标题】:Customizing each element created by the `EditorFor` helper自定义由 `EditorFor` 助手创建的每个元素
【发布时间】:2017-11-14 02:27:07
【问题描述】:

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

【问题讨论】:

  • 你对new { htmlAttributes = new {@class = "x" }}有什么要求,你想从viewmodel属性或ViewBag动态改变类'x'?
  • @TetsuyaYamamoto:不,EditorFor 能够与模型的各个成员一起搭建整个模型。自动脚手架时,我们如何为标签('text-danger')、字段('form-control')、验证('validation-error')等每种脚手架项目定义css类?

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


【解决方案1】:

您必须使用EditorTemplate,而EditorFor 助手将根据您的模板自动呈现您的模型,您无需依赖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 助手一起使用(将其放在 Shared 文件夹中,也可以放在子文件夹中以便更好地组织

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

【讨论】:

  • 模板的名称应与类相同(在这种情况下为UserModel.cshtml,并放在/Views/Shared/EditorTemplates 文件夹中 - 然后就是@Html.EditorFor(m =&gt; m)
  • @StephenMuecke:没错,但是覆盖默认行为允许您为单个模型或元素定义多个模板并在适用的情况下使用它们。
  • 是的,但是您不能将它用于收藏。在任何情况下,您都可以为每个控制器(在 /Views/ControllerName/EditorTemplates 文件夹中)拥有一个 EditorTemplate
  • @StephenMuecke:例如,假设我们需要格式化一个货币字段,以及基于特定位置的模型中的其他字段。然后我们可以这样做来动态渲染正确的模板。
  • 我实际上会使用HtmlHelper 扩展方法来做类似的事情。我并不是说你不能按照你的建议去做(我偶尔会为简单的属性这样做),但对于复杂的模型,通常的做法是将你的模板命名为与模型相同
猜你喜欢
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 2011-09-16
  • 2011-03-09
  • 1970-01-01
  • 2023-03-09
相关资源
最近更新 更多