2015-10-30 28 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