Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 })
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
498 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

<input type="checkbox" disabled>
<input type="checkbox" disabled="disabled">
<input type="checkbox" disabled="false">
<input type="checkbox" disabled="no">
<input type="checkbox" disabled="enabled">

This should work in the razor. Simple If condition and rendering what you want.

@if(item.Selected)
{ 
  @Html.CheckBoxFor(modelItem => item.Selected)
}
else
{
    @Html.CheckBoxFor(modelItem => item.Selected, new { @disabled = "disabled"})
}

You may consider writing a custom html helper which renders the proper markup for this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...