Seems like a good candidate for a special assistant:
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); } }
which can be used as follows:
@Html.TextBoxFor( m => m.PracticeName, new { style = "width:100%" }, Model.PracticeName != String.Empty )
The helper, obviously, can be done even further, so you do not need to pass an additional logical value, but it automatically determines whether the value of the default(TProperty)
expression default(TProperty)
, and it uses the disabled
attribute.
Another possibility is an extension method as follows:
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; } }
which you would use with the standard TextBoxFor
:
@Html.TextBoxFor( m => m.PracticeName, new { style = "width:100%" }.DisabledIf(Model.PracticeName != string.Empty) )
source share