【问题标题】:Html(5) attributes for EditorForEditorFor 的 Html(5) 属性
【发布时间】:2013-03-22 09:43:18
【问题描述】:

我知道这已经讨论过很多次了。

我想使用

@Html.EditorFor(u => u.Password, new { required = "required" })

不幸的是,默认情况下这是不可能的,因为 EditorFor 会覆盖 Html 属性。

我不想使用 TextBoxFor,因为我希望根据 DisplayFormat 属性对值进行格式化。

有什么解决办法吗?

【问题讨论】:

  • overwrites the HTML attributes 是什么意思?
  • @mosquito:你的问题是什么?如果您需要必填字段验证,可以在模型中进行设置。

标签: asp.net-mvc asp.net-mvc-3 html razor


【解决方案1】:

您可以为字符串类型 (~/Views/Shared/EditorTemplates/string.cshtml) 编写自定义编辑器模板:

@Html.TextBox(
    "", 
    ViewData.TemplateInfo.FormattedModelValue,
    ViewData
)

然后:

@Html.EditorFor(u => u.Password, new { required = "required" })

将按预期工作。

【讨论】:

  • 那么overwrites the HTML attributes的OP是什么意思?
  • @MichaelPerrenoud,你为什么问我?问 OP。我猜他的意思是他传递给编辑器模板的new { required = "required" } 参数没有任何效果,这是完全正常的,因为默认的编辑器模板内置 ASP.NET MVC 不使用它们。这就是为什么我建议创建一个将使用这些参数的自定义编辑器模板。
【解决方案2】:

不确定这是一个选项,但您可以将 [Required] 作为属性装饰器放在模型上。

【讨论】:

  • 不,这对我想要的 html 属性没有影响。
猜你喜欢
  • 1970-01-01
  • 2010-12-10
  • 2011-04-13
  • 2013-06-23
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
相关资源
最近更新 更多