以下示例:
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
似乎正在使用
LabelFor
的第二个重载方法,其中第二个参数,htmlAttributes
, 记录为An object that contains the Html attributes for the element
术语“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"
}
这将转换为上面显示的属性。
属性名称中的下划线被转换为破折号( How to specify data attributes in razor, e.g., data-externalid="23151" on @this.Html.CheckBoxFor(...) ),而
@
之前 @class
是必需的,因为 class
是一个保留关键字,如果不使用 @
转义就不能使用。 ( How can I add a class attribute to an HTML element generated by MVC's HTML Helpers? )。还有一个 overload accepting
IDictionary<string, object> htmlAttributes
,所以你也可以传递一个字典:new Dictionary<string, object>
{
{ "class", "some-css-class" },
{ "data-foo", "bar" }
}
关于asp.net-mvc - "HTML attributes"参数是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37589076/