Search code examples
c#asp.net.netasp.net-mvcasp.net-mvc-3

Disable checkbox in View


I am trying to disable a checkbox in my View using a Model property. However, in both the cases, the checkbox is disabled. Should I not be using "" in the following code?

<%= Html.CheckBoxFor(c => c.HasList, new { disabled = (Model.CanModifyList) ? "" : "disabled" })%>

Solution

  • Even if you have set disabled="" it is still classed as being disabled as the element will still have the disabled attribute. Without using JavaScript/JQuery you'll have to do an if statement in your View.

    Bear with me as I'm used to Razor syntax, but it should be something like:

    <%if (model.CanModifyList) { %>
    <%= Html.CheckBoxFor(c => c.HasList)%> 
    <% } else { %>
    <%= Html.CheckBoxFor(c => c.HasList, new { disabled = "disabled" })%>
    <% } %>
    

    What would be even nicer is if you created your own HTML Helper (maybe an overload to CheckBoxFor) that returned the correct HTML dependent upon the model property, that way it saves you doing additional logic in your view :)