asp.net-mvcasp.net-mvc-3html-helper

MVC 3: Conditionally Adding the Disabled Attribute with the HtmlHelpers


I have an ASP.Net MVC 3 web application and I am adding a check box to a view page using the HtmlHelper class, like this...

@Html.CheckBox("CheckBox1", true, new { @class = "Class1" })

What I want to do is conditionally add the disabled attribute based on a view state property. Basically the following would be ideal...

@Html.CheckBox("CheckBox1", true, new { @class = "Class1", @disabled = Model.ReadOnly })

Unfortunately, due to the nature of the disabled attribute, this will not work because any value assigned to the disabled attribute (even "false") will be translated as true.

I have already thought of a few solutions to get round this problem, so the question is not how can I do this. But rather, is there a simple way like the desired method above? or do I have to resort to one of the following?..

What I know I could do...

  1. Create an if/else statement and write to different Html.CheckBox lines (not great for readability - and possible with throw a mark-up warning - not sure)

  2. Skip the HtmlHelper class and hand write the tag allowing for better conditionally attributes (keeps the code shorter, but adds inconsistency)

  3. Create a custom helper that takes a "disabled" parameter (the cleanest solution, but requires undesired extra methods - probably the best option so far though)


Solution

  • Define this somewhere in your view/helpers

    @functions {
     object getHtmlAttributes (bool ReadOnly, string CssClass) 
     {
         if (ReadOnly) {
             return new { @class = CssClass, @readonly = "readonly" };
         }
         return new { @class = CssClass };
     }
    }
    

    Then use :

    @Html.TextBox("name", "value", @getHtmlAttributes(Model.ReadOnly, "test"))