以下示例:
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
似乎正在使用LabelFor
方法的第二个重载,其中第二个参数 ,htmlAttributes
记录为
包含元素的 Html 属性的对象
术语“HTML 属性”是什么意思,可用于该对象的语法是什么?
以下示例:
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
似乎正在使用LabelFor
方法的第二个重载,其中第二个参数 ,htmlAttributes
记录为
包含元素的 Html 属性的对象
术语“HTML 属性”是什么意思,可用于该对象的语法是什么?
HTML 元素可以有属性。例如:
<div class="some-css-class" data-foo="bar" />
这里div
的属性是class
和data-foo
。
Razor 的各种接受htmlAttributes
参数的 HTML 帮助函数将提供的对象转换为属性。
您可以使用匿名类型来利用它,其中它的属性被转换为属性名称,它们的值被转换为相应属性的值。
例如:
new
{
@class = "some-css-class",
data_foo = "bar"
}
这将转化为上面显示的属性。
属性名称中的下划线被转换为破折号(如何在 razor 中指定数据属性,例如 @this.Html.CheckBoxFor(...) 上的 data-externalid="23151"),并且@
前面@class
是必需的,因为class
它是保留关键字如果不使用@
(如何将类属性添加到由 MVC 的 HTML Helpers 生成的 HTML 元素?)转义,就无法使用。
还有一个重载接受IDictionary<string, object> htmlAttributes
,因此您也可以传递字典:
new Dictionary<string, object>
{
{ "class", "some-css-class" },
{ "data-foo", "bar" }
}
我尝试根据 ViewModel 属性动态设置 htmlAttributes。但是,当使用匿名类型时,如果您为每个选项使用不同的 html 属性,编译器将无法解析它。将对象命名为“对象”会在标记属性上出现编译器错误,例如@class: “对象不包含类的定义”
将对象转换为字典可以解决此问题。:
@Html.DropDownListFor(
expression: model => model.BrandId,
selectList: listItems,
optionLabel: "Select an item",
htmlAttributes: Model.IsNew
? new Dictionary<string, object> { { "class", "form-control input-xlarge" }, { "onchange", "doStuff()" } }
: new Dictionary<string, object> { { "class", "form-control input-xlarge" }, { "disabled", "disabled" } } )