5

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

Display Name
  • 4,672
  • 1
  • 33
  • 43
minchiya
  • 603
  • 1
  • 7
  • 13

4 Answers4

5

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>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

Have a look here RadioButtonFor in ASP.NET MVC 2 or for list Has anyone implement RadioButtonListFor<T> for ASP.NET MVC?

If you are using an Enum see this answer pass enum to html.radiobuttonfor MVC3

Community
  • 1
  • 1
GraemeMiller
  • 11,973
  • 8
  • 57
  • 111
  • Even if, in my case, UserType is an "enum". Should I transforme it to some other kind of object encapsulating the enum UserType ? – minchiya Sep 15 '12 at 13:25
0

Take a look into this posting, they have answered your question (albeit MVC 2, but its the same thing in this context):

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

Hope this helps

Community
  • 1
  • 1
Display Name
  • 4,672
  • 1
  • 33
  • 43
0

In the constructor of your View Model, just initialize the property to the value that you want.

public YourViewModel(){
    UserType = "type1";
}

That way your postbacks will use whatever value you want and you don't have to set the value in the controller.

arviman
  • 5,087
  • 41
  • 48