Home / ASP.NET - MVC / HtmlHelper - RadioButton

HtmlHelper - RadioButton

The HtmlHelper class has two extension methods to create a RadioButton( with the specified name, value, and html attributes.Html.RadioButtonFor creates an input text element with the specified model attribute using a lambda expression.

Example TextBox() and TextBoxFor():

public class Student
{
    public int StudentId { get; set; set; }
    [Display(Name="Name")]
    public string StudentName { get; set; set; }
    public int Age { get; set; set; }
    public string Gender { get; set; set; }
}

RadioButton()

The Html.RadioButton() method creates an element with name, isChecked and html attributes.

RadioButton method syntax

MvcHtmlString RadioButton(string name, object value, bool isChecked, object htmlAttributes)

RadioButton has many methods. Please visit MSDN for all RadioButton().

Male: @Html.RadioButton("Gender","Male")  
Female: @Html.RadioButton("Gender","Female") 

Result:

Male: 

Female: 

In the example above, we created two radio buttons for the "Gender" attribute. The second parameter is a value that will be sent to the server, if the corresponding radio button is selected. If the Male radio button is selected, the string value "Male" is assigned to the Gender property and sent to the server. The above example creates two radio buttons as shown below.

Output in the browser


RadioButtonFor

RadioButtonFor creates an element with the specified model attribute using a lambda expression.

RadioButtonFor method syntax

MvcHtmlString RadioButtonFor(> expression, object value, object htmlAttributes)

RadioButtonFor has many methods. Please visit MSDN for all RadioButtonFor.

@model Student
@Html.RadioButtonFor(m => m.Gender,"Male")
@Html.RadioButtonFor(m => m.Gender,"Female")

Result:



In the above example, the first parameter in the RadioButtonFor() method is a lambda expression that specifies the property in the Model to bind to the RadioButton element. We have created two radio buttons for the Gender property in the above example. So it creates two elements with id & name set to attribute name - Gender. The second parameter is a value that will be sent to the server when the form will be submitted.

Did you find this article helpful?

Support the author so they can write more quality articles!

Tư vấn lộ trình CNTT 🤖