Create Radio buttons in ASP.NET MVC
Learn how to generate radio button control using the HtmlHelper
in razor view in this section.
The HtmlHelper
class include two extension methods to generate a <input type="radio">
HTML control in a razor view: RadioButtonFor()
and RadioButton()
.
We will use the following Student
model class throughout this article.
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public string Gender { get; set; }
}
Html.RadioButtonFor()
The Html.RadioButtonFor<TModel, TProperty>()
extension method is a strongly typed extension method.
It generates <input type="radio">
control for the property specified using a lambda expression.
Visit docs.microsoft.com to know all the overloads of RadioButtonFor().
@model Student
@Html.RadioButtonFor(m => m.Gender,"Male")
@Html.RadioButtonFor(m => m.Gender,"Female")
<input checked="checked"
id="Gender"
name="Gender"
type="radio"
value="Male" />
<input id="Gender"
name="Gender"
type="radio"
value="Female" />
In the above example, the first parameter is a lambda expression that specifies the model property to be bind with a radio button control.
We have created two radio buttons for the Gender
property in the above example.
So, it generates two <input type="RadioButton">
controls with id and name set to property name Gender
.
The second parameter is a value that will be sent to the server when the form is submitted, here Male
will be sent if the first radio button selected, and Female
will be sent if the second radio button selected.
RadioButton()
The Html.RadioButton()
method creates an radio button element with a specified name, isChecked boolean and html attributes.
Visit docs.microsoft.com to know all the overloads of RadioButton() method.
Male: @Html.RadioButton("Gender","Male")
Female: @Html.RadioButton("Gender","Female")
Male: <input checked="checked"
id="Gender"
name="Gender"
type="radio"
value="Male" />
Female: <input id="Gender"
name="Gender"
type="radio"
value="Female" />