[英]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"
}
這將轉換為上面顯示的屬性。
屬性名稱中的下划線被轉換為破折號( 如何在 razor 中指定數據屬性,例如 @this.Html.CheckBoxFor(...) 上的 data-externalid="23151" ),並且@class
之前的@
是必需的,因為class
是一個保留關鍵字,如果不使用@
轉義就不能使用它( 如何將類屬性添加到由 MVC 的 HTML 幫助程序生成的 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" } } )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.