Conditionally include checked attribute in html.RadioButtonFor (MVC4 / Razor)

When you explicitly include a checked attribute in a hand-coded html element such as a radio button, you can use bool to determine if that attribute will exist at all on that element as shown here. For those who don't want to click on a link and give this guy some well-deserved traffic:

@{ bool agree = true; } <input type="checkbox" name="agree" value="agree" checked="@agree" />

However, let's say I want to use @Html.RadioButtonFor()

, with an object. The same doesn't happen.

@Html.RadioButtonFor(m => m.Property, "ValueOfTextBox", new { @id = "MyId", @class = "my-class", autocomplete = "off", @checked = someBoolValue })

...

The above attribute is checked="true"

or checked="false"

.

The inconsistencies between our domain model, view model and many other factors prevent us from using more interesting scaffolding ... and maybe if you include this number of attributes you might be better off not using a helper ... but is there a way to make a helper the same as normal html?

I created an additional extension method on HtmlHelper

to include a bool value that controls the existence of an attribute, but I would like to know if there is an easier / more drastic behavior to address this particular problem.

+3


source to share


1 answer


You don't really need to set the attribute checked

this way - the helper will do it for you based on the property value. For example, if your model has a property Gender

and you want to display 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 Gender

is "Female", then when the page is rendered, the second radio button will be checked. Similarly



@Html.CheckboxFor(m => m.IsMale)

      

will provide a checkbox if checked, if IsMale = true

unchecked ifIsMale = false

+3


source







All Articles