Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Enable/Disable controls on a web page using MVC Razor view engine and Extension methods

17 Oct 2013 1  
Enable/Disable control on a web page using MVC Razor view engine and Extension Methods.

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;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here