Reputation: 789
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" })%>
Upvotes: 3
Views: 4070
Reputation: 21
This gets messy if you have a lot of properties
<%= Html.CheckBoxFor(c => c.HasList, (Model.CanModifyList) ? (object)new {}:(object) new{ @disabled = true } )%>
Upvotes: 0
Reputation: 1199
@mattytommo's code can be rewritten as
@{
if (model.CanModifyList)
{
@Html.CheckBoxFor(c => c.HasList)%>
}
else
{
@Html.CheckBoxFor(c => c.HasList, new { disabled = "disabled" })
}
}
Upvotes: 0
Reputation: 56449
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 :)
Upvotes: 3