动态设置TextBoxFor HtmlHelper的禁用html属性

Ton*_*ony 8 asp.net-mvc-3

我正在尝试动态设置HtmlHelper 的disabled属性TextBoxFor

@Html.TextBoxFor(model => model.Street, 
                 new
                 {
                    @class = "", 
                    disabled = (Model.StageID==(int)MyEnum.Sth) ? "disabled" : "" 
                 })
Run Code Online (Sandbox Code Playgroud)

但即使有disabled=""它是一样的disabled="disabled".怎么解决这个问题?

Chu*_*ris 20

我在一个月前遇到了同样的问题,最后我使用了这个扩展方法

public static class AttributesExtensions
{
    public static RouteValueDictionary DisabledIf(
        this object htmlAttributes, 
        bool disabled
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        if (disabled)
        {
            attributes["disabled"] = "disabled";
        }
        return attributes;
    }
}
Run Code Online (Sandbox Code Playgroud)

之后你可以像这样使用它

@Html.TextBoxFor(
    model => model.Street, 
    new { @class = "" }.DisabledIf(Model.StageID==(int)MyEnum.Sth)
)
Run Code Online (Sandbox Code Playgroud)

编辑(在保罗评论之后):

使用的data-xxxHTML属性可以通过使用的构造被开采System.Web.Routing.RouteValueDictionary类,因为下划线不会被自动转换为负号.

请改用System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes方法:将解决此问题.

更新的代码(仅扩展方法体)

var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (disabled)
{
    attributes["disabled"] = "disabled";
}
return attributes;
Run Code Online (Sandbox Code Playgroud)

  • 接受的答案中存在一个问题.您应该调用HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)而不是新的RouteValueDictionary(htmlAttributes)HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)会将html属性名称中的任何下划线转换为连字符. (4认同)