How to set Html.RadioButtonFor as selected by default in Asp.net MVC3

The below is the code snippet of how to use the Html helper for Radio Button in Asp.net MVC.

<td> Will Accept?</td>

 <td>

@Html.RadioButtonFor(x => x.WillAccept, true)

@Html.RadioButtonFor(x => x.WillAccept, false)

</td>

 

Now how can we show one radio button selected by default? There are two ways of doing it.

The first option is to pass the “checked” html attribute as a parameter to the Html helper method by creating an anonymous object as below

<td> Will Accept?</td>

<td>

@Html.RadioButtonFor(x => x.WillAccept, true, new { @checked = “checked” })

@Html.RadioButtonFor(x => x.WillAccept, false)

</td>

The Second option is to set the value of the corresponding model property in the controller itself

public ActionResult Feedback()

{

UserResponse usr= new UserResponse();

usr.WillAccept = false;

return View(“Feedback”,usr);

}

Both work perfectly, but note that, setting the value via model overrides passing via html parameter. So if both of the above options are used the default value of the radio button will be false.

Leave a reply if you find it useful


3 Comments on “How to set Html.RadioButtonFor as selected by default in Asp.net MVC3”

  1. stuart clark says:

    cheers mate!

  2. Marquis Broudy says:

    I have to thank you for the efforts you have put in penning this site. I am hoping to view the same high-grade content from you in the future as well. In truth, your creative writing abilities has encouraged me to get my very own blog now 😉

  3. Chami says:

    copy and paste doesn’t working for @Html.RadioButtonFor(x => x.WillAccept, true, new { @checked = “checked” }). lol. make sure you typed double quotes.


Leave a comment