【问题标题】:EditorFor htmlAttributes not working for type bool (MVC 5.2)EditorFor htmlAttributes 不适用于 bool 类型(MVC 5.2)
【发布时间】:2025-12-30 07:35:06
【问题描述】:

从 MVC 5.1 开始,可以向编辑器模板添加 html 属性,如下所示:

@Html.EditorFor(m => m.Foo, new { htmlAttributes = new { id = "fooId", @class="fooClass" } })

如果属性Foo 的类型为string,它将正确生成输入标记,包括自定义属性。

但如果属性Foo 的类型为bool(或bool?),则属性将被忽略...

我在这里遗漏了什么吗?难道生成“选择”标记的模板仍然不支持此功能?

【问题讨论】:

  • 你确定吗?对我来说一切正常。所有属性都包含在 bool 属性中。
  • 是的!如果我只是将属性类型更改为string,则不会忽略属性。

标签: asp.net-mvc editorfor


【解决方案1】:

我知道这个问题是不久前被问到的,但我刚才遇到了完全相同的问题。事实证明,另一个开发人员在我们的解决方案中为布尔创建了一个自定义编辑器模板,以便能够自定义下拉列表的文本。您的代码应该适用于开箱即用的编辑器,但它不会自动适用于自定义编辑器......您必须自己实现它。

如果这是您的问题,您需要修改自定义编辑器模板以从 ViewData 中提取 htmlAttributes 并将它们传递给底层的 DropDownListFor(或您正在使用的任何帮助程序)。这是我的自定义编辑器模板现在的样子:

@model bool?
@using System.Web.Mvc;
@{
    var htmlAttributes = ViewData["htmlAttributes"] ?? new { };

    @Html.DropDownListFor(model => model,
        new List<SelectListItem>(3) { 
        new SelectListItem { Text = "Unknown", Value = "" },
        new SelectListItem { Text = "Yes", Value = "true", Selected = Model.HasValue && Model.Value },
        new SelectListItem { Text = "No", Value = "false", Selected = Model.HasValue && !Model.Value }
    }, htmlAttributes)
}

此解释和解决方案的功劳归于https://cpratt.co/html-editorfor-and-htmlattributes

【讨论】: