My ViewModel has a property of selected and selectable. Both are boolean. I would like my view to have a checkbox that is enabled when selectable is true and disabled when selectable is false. What is the proper razor syntax to accomplish this ?
I tried the code below on a list of items in a table. Every row comes back with a disabled checkbox regardless of selectable value.
@Html.CheckBoxFor(modelItem => item.Selected, new { @disabled = !item.Selectable })
This won't work because
<input disabled="anything" />
will result in a disabled control. You need to only have a @disabled property when it should be disabled.Try something like this:
Note that you might need to cast to
(object)
Sorry, my previous answer was wrong.
The input-element will be disabled as soon as it gets the attribute disabled. It doesn't matter if the value is true, false. In HTML you can't set disabled to false.
So you will have to set the disabled attribute only when the condition is valid.
something like:
It is not easy to achieve this with an
if
condition inside the helper method because all the below markups will render a disabled chechbox.This should work in the razor. Simple If condition and rendering what you want.
You may consider writing a custom html helper which renders the proper markup for this.