设置可选的禁用属性

Chu*_*ris 5 html asp.net-mvc asp.net-mvc-3

我想禁用表单中的所有字段,这些字段在加载页面时具有值.例如在这

<td>@Html.TextBoxFor(m => m.PracticeName, new { style = "width:100%", disabled = Model.PracticeName == String.Empty ? "Something Here" : "disabled" })</td>
Run Code Online (Sandbox Code Playgroud)

我想写内联这样的东西.我不想使用if-else并使我的代码更大.使用javascript/jquery也不受欢迎.

我试着编写false/true,但是1.它可能不是跨浏览器2.Mvc将其解析为字符串,如"True"和"False".那我该怎么办呢?

PS我使用ASP.NET MVC 3 :)

Dar*_*rov 6

似乎是自定义助手的一个很好的候选者:

public static class HtmlExtensions
{
    public static IHtmlString TextBoxFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> ex,
        object htmlAttributes,
        bool disabled
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        if (disabled)
        {
            attributes["disabled"] = "disabled";
        }
        return htmlHelper.TextBoxFor(ex, attributes);
    }
}
Run Code Online (Sandbox Code Playgroud)

可以像这样使用:

@Html.TextBoxFor(
    m => m.PracticeName, 
    new { style = "width:100%" }, 
    Model.PracticeName != String.Empty
)
Run Code Online (Sandbox Code Playgroud)

帮助器显然可以更进一步,因此您不需要传递额外的布尔值,但它会自动确定表达式的值是否等于default(TProperty)并应用该disabled属性.

另一种可能性是这样的扩展方法:

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)

您将使用标准TextBoxFor助手:

@Html.TextBoxFor(
    m => m.PracticeName, 
    new { style = "width:100%" }.DisabledIf(Model.PracticeName != string.Empty)
)
Run Code Online (Sandbox Code Playgroud)