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
I had this same problem and decided to write my own HtmlHelper
extension method.
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 will accept a boolean to indicate if the control should be disabled or not. It just appends disabled="disabled"
just inside the first >
it comes across in a string.
You can use it like below.
@Html.TextBoxFor(model => model.ProposalName).Disable(true)