【问题标题】:Html Attributes on EditorFor() or Check dataType in EditorTemplateEditorFor() 上的 Html 属性或检查 EditorTemplate 中的数据类型
【发布时间】:2014-02-25 14:28:24
【问题描述】:

我有一个类,其属性 Password 注释为 DataType.Password,如下所示:

[DataType(DataType.Password)]
[Required]
public string Password { get; set; }

当我使用 EditorFor 在视图上显示此字段时,我需要在其上应用 CSS 类。

我是这样做的:

@Html.EditorFor(model => model.Password, "loginTextBox", new { @class = "form-control ", placeholder = "" })

由于某种原因,没有内置的方式为 EditorFor() 使用 Html 属性(例如我可以在这里阅读:Html attributes for EditorFor() in ASP.NET MVC),所以我需要创建一个简单的 EditorTemplate 来允许它像这样:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = ViewData["class"], id = ViewData["id"], placeholder = ViewData["placeholder"]})

问题是,这个编辑器在不是 DataType.Password 的其他属性之间共享。如果属性被注释为 DataType.Password 我想使用

@Html.Password(...)

否则

@Html.TextBox(...)

我能想到的唯一方法是检查 DataType,但我不知道如何做到这一点。

关于如何检查 DataType 甚至更好的方法的任何想法?

【问题讨论】:

  • 您使用什么版本的 asp.net MVC? ASP.Net MVC 5 支持html attributes for EditorFor
  • 您可以为此专门编写自己的 EditorTemplate。
  • 这不是真的#Murali。在这里查看:msdn.microsoft.com/en-us/library/…
  • #jacqijvv 我知道我可以做一个特定的,但是 Datatype.Password 失去了它的所有意义。
  • @lpaloub,请查看ASP.Net MVC 5.1 Release notes@Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" }, })

标签: c# html asp.net asp.net-mvc


【解决方案1】:

现在 ASP.Net MVC 5.1 支持 htmlAttributes 用于 EditorFor。只需将其作为匿名对象传递即可。

ASP.Net MVC 5.1 Release Notes

@Html.EditorFor(model => model.Password, "loginTextBox",
 new { htmlAttributes = new { @class = "form-control ", placeholder = ""})

【讨论】:

  • 这可能对每个人都没有用(不是每个人都可以更新),但是由于我刚刚开始创建网站,所以这个解决方案对我来说是完美的。再次感谢!
  • 如何将提示元数据与新的 EditorFor 一起使用?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-13
  • 1970-01-01
  • 2010-12-10
  • 2019-09-29
  • 2013-10-20
  • 1970-01-01
  • 2018-07-01
相关资源
最近更新 更多