I have a C# .Net web app. In that app I need to conditionally disable Html.TextBoxFor controls (also Html.DropDownListFor controls) based on who is
The solution posted by @epignosisx works, but it may be a problem if you want to add some other attribute because you will have to add it it both objects (the one with disabled and the one now its empty).
Even worse if you have some other bool property because you will have four different objects, each one for each combination.
The best solution here (with a little more code) is to build an extension method for HtmlHelper to receive your boolean property as a parameter.
public static MvcHtmlString TextBoxDisabledFor(this HtmlHelper htmlHelper, Expression> expression, bool disabled, object htmlAttributes = null)
{
return TextBoxDisabledFor(htmlHelper, expression, disabled, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString TextBoxDisabledFor(this HtmlHelper htmlHelper, Expression> expression, bool disabled, IDictionary htmlAttributes)
{
if (htmlAttributes == null)
htmlAttributes = new Dictionary();
if (disabled)
htmlAttributes["disabled"] = "disabled";
return htmlHelper.TextBoxFor(expression, htmlAttributes);
}
Here there is another example