For a view, I've to generate some checkbox.
I've one collection of items:
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'm iterating on 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 a "if" in which I create a different HtmlAttribute array, depending of 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.
You can't avoid the if
:
The problem is with the special nature of the disabled
attribute because there is no "special" value which would make your sample work, because:
"disabled" is only possible value for this attribute. If the input should be enabled, simply omit the attribute entirely.
So you need to omit the attribute to enable the control but all HTML helpers will serialize all the properties of the anonymous objects passed in as the htmlattributes. And there is no way to conditionally add properties to anonymous types.
However if you have multiple common attributes for the enable/disable case, and you don't want to create two anonymoues types, you can put the attributes in a dictionary with the optional disabled
attribute and use the dictionary as the htmlAttributes:
var checkboxHtmlAttributes = new Dictionary<string, object>
{{"attibute1", "value1"},
{"attribute2", "value2"}};
if (!item.IsActive)
{
checkboxHtmlAttributes.Add("disabled", "disabled");
}
@Html.CheckBoxFor(m=>item.IsSelected, checkboxHtmlAttributes)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With