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
Extending @James's answer, I wrote this HtmlHelper extension that updates/removes the disabled attribute if it's already present, or adds it if not:
public static MvcHtmlString Disable(this MvcHtmlString helper, bool disabled) {
string html = helper.ToString();
var regex = new Regex("(disabled(?:=\".*\")?)");
if (regex.IsMatch(html)) {
html = regex.Replace(html, disabled ? "disabled=\"disabled\"" : "", 1);
} else {
regex = new Regex(@"(\/?>)");
html = regex.Replace(html, disabled ? "disabled=\"disabled\"$1" : "$1", 1);
}
return MvcHtmlString.Create(html);
}
It also plays nicely with self-closing tags (like ).
Usage is the same:
@Html.TextBoxFor(model => model.PropertyName).Disable(true)
Tested on both @Html.DropDownListFor() and @Html.TextBoxFor().