Razor 有三种不同的方式来设置 "class" 属性

Razor has three different ways to set "class" attribute

这是 ASP .NET MVC5 项目中 "Add View" 向导生成的代码:

    <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>

如您所见,可以通过三种不同的方式在 html 控件上设置 "class" 属性。为什么会出现这种异常?另外,一个比另一个更受欢迎吗?问候。

都是一样的!

我更喜欢这个htmlAttributes: new { @class = "control-label col-md-2" }因为它显示了参数名clearly.Otherwise,其他两个选项都不错

第一个和第三个是一样的。第一个是命名参数。您可以使用这种方式更加清晰,但这不是必需的。

但是第二个示例将 html 属性传递给另一个对象,该对象对其进行聚合。而且您不能将这种方式用于前两个。在 MVC 源中,此对象转换为 KeyValuePair:

if (additionalViewData != null)
{
    foreach (KeyValuePair<string, object> kvp in TypeHelper.ObjectToDictionary(additionalViewData))
    {
        viewData[kvp.Key] = kvp.Value;
    }
}