When you explicitly include the checked attribute in a manually coded html element such as a radio button, you can use a bool to determine if that attribute will exist at all on that element as seen here. For those not wanting to click the link and give this guy some well deserved traffic:
@{
bool agree = true;
}
<input type="checkbox" name="agree" value="agree" checked="@agree" />
However, lets say that I want to use @Html.RadioButtonFor()
, with the an object. The same does not occur.
@Html.RadioButtonFor(m => m.Property, "ValueOfTextBox", new { @id = "MyId", @class = "my-class", autocomplete = "off", @checked = someBoolValue })
.
The above gives a checked="true"
or checked="false"
attribute.
Discrepancies between our Domain Model, View Model, and many other things are keeping us from being able to use some more interesting scaffolding... and arguably if you're including this number of attributes you may be better off just not using the helper... but is there a way to make the helper have the same behavior as the plain html?
I've created an additional extension method on HtmlHelper
to include a bool value that controls the presence of the attribute, but I would love to find out if there is a more straightforward/framework behavior way to solve this particular issue.
You really don't need to set the checked
attribute this way - the helper will do it for you based on the value of the property. For example if your model has property Gender
and you want to render radio buttons for "Male" and "Female"
@Html.RadioButtonFor(m => m.Gender, "Male")<span>Male</span>
@Html.RadioButtonFor(m => m.Gender, "Female")<span>Female</span>
and the value of Gender
is "Female", then when the page is rendered the second radio button will be checked. Similarly
@Html.CheckboxFor(m => m.IsMale)
will render the checkbox as checked if IsMale = true
and unchecked if IsMale = false