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
The problem is when you have to add more than 1 HTML attribute. That's a mess:
@if(item.Selected)
{
@Html.CheckBoxFor(modelItem => item.Selected, new { @data_foo = "bar"})
}
else
{
@Html.CheckBoxFor(modelItem => item.Selected, new { @data_foo = "bar", @disabled = "disabled"})
}
What I do to solve this is to use a IDictionary that is previously loaded:
var htmlAttributes = new Dictionary{
{"data-foo", "bar"}
};
if(!item.Selected)
{
htmlAttributes.Add("@disabled", "disabled");
}
And then I create the checkbox component only once:
@Html.CheckBoxFor(modelItem => item.Selected, htmlAttributes)