Flexabust Bergson Flexabust Bergson - 1 year ago 86
C# Question

Can't get default check on RadioButtonFor

I have a razor

RadioButtonFor
that I am trying to check by default but nothing works. Here is my Code:

@Html.RadioButtonFor(m=>m.selected, new {@checked=true});


Where
selected
is a boolean. And the Html Generated:

<input name="selected" id="selected" type="radio"
value="{ Name = groupRadio, checked = True }">


I've also tried

@Html.RadioButtonFor(m=>m.selected, 0, new {@checked=true});


which didn't work either. Any ideas?

Thanks

Answer Source

If selected is bool, then your radio buttons need to be

<label>
    @Html.RadioButtonFor(m=>m.selected, true, new { id = "" });
    <span>Yes</span>
</label>
<label>
@Html.RadioButtonFor(m=>m.selected, false, new { id = "" });
    <span>No</span>
</label>

Note the 2nd parameter generates the value attribute to bind to your bool property.

Then if the value of selected is true, the first will be selected, otherwise the 2nd will be

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download