How to have conditional checkbox disabled, ... using html helper?

For presentation I have to create some checkbox.

I have one set of elements:

public class ItemSelection { public int Id { get; set; } public String Name { get; set; } public Boolean IsSelected { get; set; } public Boolean IsActive { get; set; } } 

and in the view I repeat this

 @foreach(ItemSelection item in Model.Items){ Html.CheckBoxFor(m=>item.IsSelected)//HERE I WOULD LIKE TO HAVE DISABLED properties if I've a IsActive=falsel Html.HiddenFor(m=>item.Id) } 

Now I see that I can do an “if” in which I create another HtmlAttribute array, depending on this property, but is there a way to create only one array

 new {disabled=item.IsActive?"ONE_SPECIAL_VALUE_HERE":"disabled"} 

I tried to put false or some other things, nothing worked.

+7
source share
1 answer

You cannot escape if :

The problem is related to the special nature of the disabled attribute, because there is no special value that would make your sample work because :

"disabled" is the only possible value for this attribute. If the input should be enabled, simply omit the entire attribute.

So, you need to omit the attribute to enable the control, but all HTML helpers serialize all the properties of anonymous objects passed as html attributes. And there is no way to conditionally add properties to anonymous types.

However, if you have several common attributes for the enable / disable case, and you do not want to create two types of anonymoues, you can put the attributes in a dictionary with the optional disabled attribute and use the dictionary as htmlAttributes:

 var checkboxHtmlAttributes = new Dictionary<string, object> {{"attibute1", "value1"}, {"attribute2", "value2"}}; if (!item.IsActive) { checkboxHtmlAttributes.Add("disabled", "disabled"); } @Html.CheckBoxFor(m=>item.IsSelected, checkboxHtmlAttributes) 
+8
source

All Articles