以下是从"添加视图"生成的代码ASP .NET MVC5项目中的向导:
<div class="form-group">
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
</div>
</div>
正如你所看到的,&#34; class&#34;有三种不同的方式。属性是在html控件上设置的。为什么这个异常?另外,一个优先于另一个吗?问候。
答案 0 :(得分:1)
第1和第3是相同的。第一个是命名参数。您可以使用这种方式更清晰,但这不是必需的。
但是第二个例子将html属性传递给另一个聚合它的对象。你不能用这种方式前两个。在MVC源中,此对象将转换为KeyValuePair:
if (additionalViewData != null)
{
foreach (KeyValuePair<string, object> kvp in TypeHelper.ObjectToDictionary(additionalViewData))
{
viewData[kvp.Key] = kvp.Value;
}
}
答案 1 :(得分:0)
他们都是一样的!
我更喜欢这个htmlAttributes: new { @class = "control-label col-md-2" }
,因为它清楚地显示了参数名称。否则,其他两个选项都很好。