5

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?

Fillip Peyton
  • 3,637
  • 2
  • 32
  • 60
  • An alternative is [this answer](http://stackoverflow.com/questions/33892728/asp-net-mvc-inserts-string-inside-new-object-parameter/33892904#33892904) but disabling a checkbox generated by `CheckBoxFor` means that it will always post back `false` even if the checkbox is checked which would cause binding to fail –  Jan 20 '16 at 00:41
  • Please reference this:http://stackoverflow.com/questions/8061647/conditional-html-attributes-using-razor-mvc3 – Logan B. Lehman Jan 20 '16 at 00:54

2 Answers2

10

While you could use

@Html.CheckBoxFor(m => m.Property, Model.IsAuthorized ? (object)new { @class = "input-class", disabled = "disabled" } : (object)new { @class = "input-class"});

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 with value="True" and a hidden input with value="False". In the case where the initial value of Property is true and IsAuthorized is true 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 in Property being false (when it should be true)

In order to handle model binding correctly, you will need the if block

@if (Model.IsAuthorized)
{
    @Html.CheckBoxFor(x => m.Property, new { @class = "input-class" })
}
else
{
    @Html.HiddenFor(m => m.Property) // necessary to post back the initial value
    <input type="checkbox" @(Model.Property ? "checked" : null) disabled />
}
-1

Try the below code:

@{
 var attr = new { @class = "input-class" };
 if (Model.IsAuthorized)
 {
    attr = new { @class = "input-class", @disabled = "disabled" };
 }
}
@Html.CheckBoxFor(x => @Model.Property, attr)
Rahul Mahadik
  • 794
  • 11
  • 19