2015-10-30 31 views
0

我爲Northwinds DB's product表創建了腳手架視圖。我瞭解到它正在創建匿名類型new {@class...。但是,我不明白以下代碼中的部分htmlAttributes:。它在做什麼?htmlAttributes:在Html.LabelFor中

@Html.LabelFor(model => model.UnitsInStock, 
    htmlAttributes: new { @class = "control-label col-md-2" }) 

它和new { htmlAttributes = new { @class = "form-control" }這個代碼有什麼不同?我希望我能正確地問問題。我使用MVC 5與Visual Studio 2015

+2

它只是使'新{@class = 「控制標籤COL-MD-2」}'目的是擴展方法的'htmlAttributes'參數。你也可以使用'@ Html.LabelFor(model => model.UnitsInStock,new {@class =「control-label col-md-2」})'(即不顯式使用'htmlAttributes:' –

+0

)參數功能在C#? –

+0

..進一步闡明html屬性是使用命名參數'htmlAttributes:'傳遞的。這是C#中的一個很棒的功能。更多信息https://msdn.microsoft.com/en-us/library/dd264739.aspx – niksofteng

回答

2

htmlAttributes:被指定一個命名的參數,因此它被傳遞匿名對象(new { @class = "control-label col-md-2")到LabelFor()方法的htmlAttributes參數。

在這種情況下,它不是絕對必要的,因爲LabelFor()overload它接受公正的表達和object所以它也可能只是

Html.LabelFor(m => m.UnitsInStock, new { @class = "control-label col-md-2" }) 

但使用命名參數允許您指定的參數任何順序的方法。

還請參考文檔Named and Optional Arguments