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

About these ads

2 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 ;)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.