以下样本:
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })似乎正在使用LabelFor方法的第二个重载,其中第二个参数htmlAttributes被记录为
包含元素的Html属性的对象
"HTML属性“一词意味着什么?这个对象可以使用什么语法?
发布于 2016-06-02 10:22:11
HTML元素可以具有属性。例如:
<div class="some-css-class" data-foo="bar" />这里,div的属性是class和data-foo。
剃刀的各种helper函数接受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?)转义,就不能使用class。
还有一个IDictionary htmlAttributes,所以您也可以传递一本字典:
new Dictionary<string, object>
{
{ "class", "some-css-class" },
{ "data-foo", "bar" }
}发布于 2020-03-02 08:09:43
我尝试基于一个htmlAttributes属性动态地设置ViewModel。但是,当使用匿名类型时,如果您对每个选项使用不同的html属性,编译器就无法解析它。命名对象' object‘会在标记属性上出现编译器错误,例如@class:"Object不包含类的定义“
将对象转换为字典解决了这个问题。
@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" } } )https://stackoverflow.com/questions/37589076
复制相似问题