I am using a Html helper to create a checkbox. Pending some condition, I want to add the disabled
attribute to the htmlAttribute object. I have the following code:
@if (Model.IsAuthorized)
{
@Html.CheckBoxFor(x => @Model.Property, new { @class = "input-class" })
}
else
{
@Html.CheckBoxFor(x => @Model.Property, new { @class = "input-class", @disabled = "disabled" })
}
I'd like to make this code more terse. Is there a way to conditionally add certain html attributes in one line/without a block conditional?
While you could use
to do this in one line of code, in your case it may result in model binding failing.
The
CheckBoxFor()
method generates 2 inputs, a checkbox withvalue="True"
and a hidden input withvalue="False"
. In the case where the initial value ofProperty
istrue
andIsAuthorized
istrue
the result is that the checkbox is disabled and will not post a value. However the hidden input will be submitted and bind to your model, resulting inProperty
beingfalse
(when it should betrue
)In order to handle model binding correctly, you will need the
if
block