Set @Html.RadioButtonFor as Checked by default
-
02-07-2021 - |
Question
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
Solution
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
OTHER TIPS
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>
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
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.