Set @Html.RadioButtonFor as Checked by default

minchiya picture minchiya · Sep 15, 2012 · Viewed 21.1k times · Source

I am not able to set the default radio button to "Checked" ! I am using @Html.RadioButtonFor :

<div id="private-user">
    @Html.RadioButtonFor(m => m.UserType, "type1", new { @class="type-radio" , **@Checked="checked"** }) 1
</div>
<div id="proff-user">
    @Html.RadioButtonFor(m => m.UserType, "type2", new { @class="type-radio" }) 2
</div>

Is it possible to set a radio button as cheched using @Html.RadioButtonFor ?

Thx

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 15, 2012

In your controller action set the value of the UserType property on your view model to the corresponding value:

public ActionResult SomeAction()
{
    MyViewModel model = ...

    // preselect the second radio button
    model.UserType = "type2";
    return View(model);
}

and in your view:

<div id="private-user">
    @Html.RadioButtonFor(m => m.UserType, "type1", new { @class="type-radio" }) 1
</div>
<div id="proff-user">
    @Html.RadioButtonFor(m => m.UserType, "type2", new { @class="type-radio" }) 2
</div>