Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox disabled attribute in ASP.NET MVC

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 }) 
like image 205
Bill Greer Avatar asked Jan 05 '14 23:01

Bill Greer


People also ask

How check checkbox is checked or not in ASP NET MVC?

This blog defines how to get checked property of Checkbox in MVC. Create a View with Checkbox. aspx Page. Run and click on button after selectin checkbox and see results.


1 Answers

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.

like image 53
Shyju Avatar answered Sep 17 '22 14:09

Shyju