Disabling an ASP.NET MVC input control
I love ASP.NET MVC. It is a great framework to get web apps quickly built. However using the built in HtmlHelper methods on your views isn’t without its issues.
An example of this is when trying to disable a HTML input control which has been built using HtmlHelper. You can add the “disabled” attribute which would be required by making use of one of the helper’s overloads however if you want to conditionally disable a control (based on your view model) it can result in your view’s code becoming more inflated than you might have initially though it would need to be!
To try and help with this I created a simple extension which will add the required attribute based on a passed in boolean value.
public static MvcHtmlString Disable(this MvcHtmlString helper, bool disabled) {
if (helper == null)
throw new ArgumentNullException();
if (disabled)
{
string html = helper.ToString();
int startIndex = html.IndexOf('>');
html = html.Insert(startIndex, " disabled=\"disabled\"");
return MvcHtmlString.Create(html);
}
return helper;
}
This is a very simplistic helper which can be improved upon but it served it’s need when it was created.
It can be used as follows.
@Html.TextBoxFor(model => model.ProposalName).Disable(true)