Wednesday 1 May 2019

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>

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, truenew { @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

No comments:

Post a Comment

What is Agile,advantage and disadvantages

Introduction:- It is a software development life cycle used for software development, that is characterized by the division of tasks in...