什么是"HTML属性"?范围? [英] What is the "HTML attributes" parameter?
问题描述
以下示例:
@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的各种HTML帮助器函数接受htmlAttributes
参数,将提供的对象转换为属性.
您可以使用匿名类型来利用此属性,该属性的属性会转换为属性名称,其值会转换为相应属性的值.
例如:
new
{
@class = "some-css-class",
data_foo = "bar"
}
这将转换为上面显示的属性.
属性名称中的下划线会转换为破折号(@ >是必需的,因为class
是保留关键字,如果不使用@
转义(过载接受IDictionary<string, object> htmlAttributes
,因此您也可以通过字典:
new Dictionary<string, object>
{
{ "class", "some-css-class" },
{ "data-foo", "bar" }
}
The following sample:
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
appears to be using the second overload of the LabelFor
method where the second parameter, htmlAttributes
, is documented as
An object that contains the Html attributes for the element
What does the term "HTML attributes" mean and what is the syntax that can be used for this object?
HTML elements can have attributes. For example:
<div class="some-css-class" data-foo="bar" />
Here the div
's attributes are class
and data-foo
.
Razor's various HTML helper functions that accept an htmlAttributes
argument translate the provided object to attributes.
You can utilize this using an anonymous type where its properties are translated to attributes names, and their values to the respective attribute's value.
For example:
new
{
@class = "some-css-class",
data_foo = "bar"
}
This will translate to the attributes shown above.
Underscores in property names get translated to dashes (How to specify data attributes in razor, e.g., data-externalid="23151" on @this.Html.CheckBoxFor(...)), and the @
before @class
is required because class
is a reserved keyword that can't be used without escaping it with an @
(How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?).
There's also an overload accepting IDictionary<string, object> htmlAttributes
, so you could instead pass a dictionary as well:
new Dictionary<string, object>
{
{ "class", "some-css-class" },
{ "data-foo", "bar" }
}
这篇关于什么是"HTML属性"?范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!