Introduction
When developing using ASP.NET MVC razor view engine there is sometime the need of disabling/enabling controls if a certain condition is verified.
The common example is when we want to disable a textbox if, let's say, a Boolean property on the Viewmodel is True.
In the below example we got a registration form and we want to disable the user name Textbox when the
IsEditMode
property is false.
What we should do is checking IsEditMode
and if it is true disable the Textbox.
<li>
@Html.LabelFor(m => m.UserName)
@if (Model.IsEditMode==false)
{
@Html.TextBoxFor(m => m.UserName,new{disabled="disabled"})
}
else
{
@Html.TextBoxFor(m => m.UserName)
}
</li>
Using the code
With the extension method described in this article will be possible to achieve the same behavior using the code below:
<div>
@Html.TextBoxFor(m => m.UserName).DisableIf(()=> Model.IsEditMode==false)
</div>
The above code is more readable and easy to maintain.
The extensions method code is showed below:
public static class DisableHtmlControlExtension
{
public static MvcHtmlString DisableIf(this MvcHtmlString htmlString, Func<bool> expression)
{
if (expression.Invoke())
{
var html = htmlString.ToString();
const string disabled = "\"disabled\"";
html = html.Insert(html.IndexOf(">",
StringComparison.Ordinal), " disabled= " + disabled);
return new MvcHtmlString(html);
}
return htmlString;
}