3

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" })%>

3 Answers 3

3

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 :)

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah. I was trying to see if I could use the conditional operator and do without using the if/else.
@dotNetNewbie yeah the only way to do that would be a Html Helper :)
0

@mattytommo's code can be rewritten as

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

Comments

0

This gets messy if you have a lot of properties

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.