Razor属性在Text Field和Password Field上

时间:2017-05-14 13:31:54

标签: c# asp.net-mvc razor

我正在使用ASP.NET MVC 5.

文字字段(请注意htmlAttributes):

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

密码字段(注意缺少htmlAttributes):

@Html.PasswordFor(model => model.Passwd, new {@class = "form-control"})

这是我能让它发挥作用的唯一方法。

在文本字段上,如果我带走了htmlAttributes,它就不起作用。

在“密码”字段中,如果我添加htmlAttributes,则无效。

为什么???

2 个答案:

答案 0 :(得分:2)

在我看来,这些方法签名的区别在于。 PasswordFor具有以下签名:

MvcHtmlString Html.PasswordFor(Expression<Func<dynamic,TProperty>> expression, object htmlAttributes)

其中第二个参数是表示htmlAttributes的对象。因此,在这种情况下,您只是使用构造函数语法创建此htmlAttributes对象并将其作为参数传递。

然而,EditorFor有点不同:

EditorExtensions.EditorFor<TModel, TValue> Method (HtmlHelper<TModel>, Expression<Func<TModel, TValue>>, Object)

其中第二个参数是包含additionalViewData的对象。据我所知,htmlAttributes可以是此对象的属性。因此,在这种情况下,您使用对象初始值设定项语法进行对象创建,您可以使用htmlAttributes的值设置new { @class = "form-control" }属性。

答案 1 :(得分:1)

<强> PasswordFor:

Html.PasswordFor()方法生成具有指定名称,值和html属性的输入密码元素。    签名示例:

 public static MvcHtmlString PasswordFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes);

<强> EditorFor:

这个控件有点聪明。它根据属性的数据类型呈现HTML标记。您可以传入一个匿名对象,其属性将以某种方式作为属性添加到某个标记上,尤其是对于内置编辑器模板。您需要编写自己的自定义编辑器模板,并将所需的值作为附加的viewdata传递。

签名示例:

public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object additionalViewData);