Skip to content Skip to sidebar Skip to footer

Set Optional Disabled Attribute

I want to disable all fields in my form, which have values when page is loaded. For example in this @Html.TextBoxFor(m => m.PracticeName, new { style = 'width:100%', d

Solution 1:

Seems like a good candidate for a custom helper:

publicstaticclassHtmlExtensions
{
    publicstatic 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);
    }
}

which could be used like this:

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

The helper could obviously be taken a step further so that you don't need to pass an additional boolean value but it automatically determines whether the value of the expression is equal to default(TProperty) and it applies the disabled attribute.

Another possibility is an extension method like this:

publicstaticclassAttributesExtensions
{
    publicstatic RouteValueDictionary DisabledIf(thisobject htmlAttributes, 
        bool disabled
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        if (disabled)
        {
            attributes["disabled"] = "disabled";
        }
        return attributes;
    }
}

which you would use with the standard TextBoxFor helper:

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

Post a Comment for "Set Optional Disabled Attribute"