RadioButton HTML Helper in ASP.NET Core MVC

RadioButton HTML Helper in ASP.NET Core MVC

In this article, I am going to discuss How to Generate Radio Buttons using RadioButton HTML Helper in ASP.NET Core MVC Application with Examples. Please read our previous article, where we discussed How to Generate DropDownList using HTML Helper in ASP.NET Core MVC.

What is a Radio Button?

A radio button, also known as a radio input or option button, is a graphical user interface (GUI) element that allows users to select a single option from a list of mutually exclusive choices. It’s often used in forms and dialog boxes to present users with a set of options where only one can be chosen. Radio buttons are typically circular or elliptical in shape and are used to indicate the user’s selection.

Key Characteristics of Radio Buttons:
  • Mutually Exclusive: Radio buttons in a group are designed to be mutually exclusive, meaning that only one option can be selected at a time. When a user selects a new option, any previously selected option within the same group becomes deselected.
  • Grouping: To enforce mutual exclusivity, radio buttons are grouped together using the same name attribute in HTML. This ensures that they behave as a single unit, and only one option can be selected within that group.
  • Labels: Radio buttons are often accompanied by labels that describe each option. Clicking on the label associated with a radio button can also select the button, enhancing user experience by providing a larger clickable area.
  • State Indicator: When selected, a radio button typically displays a small dot or circle inside it to indicate the chosen option.
  • HTML Structure: In HTML, a radio button is represented by an <input> element with a type attribute set to “radio”. Each radio button within a group should have the same name attribute and a unique value attribute.
  • Use Cases: Radio buttons are commonly used for situations where users need to make a single choice from a predefined set of options, such as selecting a gender, choosing a payment method, or indicating a preference.
Example of Radio Buttons in HTML:
<input type="radio" id="option1" name="choice" value="option1">
<label for="option1">Option 1</label><br>

<input type="radio" id="option2" name="choice" value="option2">
<label for="option2">Option 2</label><br>

<input type="radio" id="option3" name="choice" value="option3">
<label for="option3">Option 3</label><br>

In the above example, three radio buttons share the same name attribute, choice, which groups them together as a set of options. Users can select one option by clicking the associated label or the radio button itself.

RadioButton HTML Helper in ASP.NET Core MVC

In ASP.NET Core MVC, the RadioButton HTML Helper is used to generate HTML markup for radio button inputs within a view. Radio buttons are often used when we want users to select one option from a list of mutually exclusive options.

How to Generate Radio Buttons in ASP.NET Core MVC?

The HtmlHelper class provides two extension methods that are used to generate a <input type=”radio”> element in a view. The two methods are as follows:

  • RadioButton()
  • RadioButtonFor()
RadioButton HTML Helper Method in ASP.NET MVC:

The Html.RadioButton() HTML Helper method in ASP.NET Core MVC Application is used to create a radio button element with a specified name, isChecked boolean property, and the HTML attributes. The Html.RadioButton() HTML Helper method is a loosely typed method.

Example to Understand the RadioButton Helper Method:

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

If you inspect the HTML, then you will see the following HTML

Male: <input id="Gender" name="Gender" type="radio" value="Male" />
Female: <input id="Gender" name="Gender" type="radio" value="Female" />

In the above example, we have created two radio buttons, Male and Female, for the Gender property. The first parameter is the group name. The point that you need to keep in mind is that you need to give the same name to both the radio buttons. The second parameter is the value of the radio button, which will be sent to the server when the respective radio button is checked. That means if the Male radio button is selected, the string value Male will be assigned to a model property named Gender and submitted to the server.

RadioButtonFor HTML Helper in ASP.NET Core MVC:

The RadioButtonFor HTML Helper method is the strongly typed extension method. It also generates an <input type=”radio”> element in a view. Here, we need to specify the name for the Radio Button using a lambda expression. The RadioButtonFor HTML Helper method binds a specified model object property to RadioButton control. As a result, it automatically checked or unchecked the RadioButton based on the property value.

Example to Understand RadioButtonFor HTML Helper in ASP.NET Core MVC

To understand this, let’s create a new model. Right-click on the Models folder and then add two class files with the name Company.cs and Department.cs. Copy and paste the following code once you create the class files.

Department.cs
namespace HTML_HELPER.Models
{
    public class Department
    {
        public int Id { get; set; }
        public string? Name { get; set; }
    }
}
Company.cs
namespace HTML_HELPER.Models
{
    public class Company
    {
        public int SelectedDepartment { get; set; }
        public List<Department> Departments()
        {
            List<Department> ListDepartments = new List<Department>()
            {
                    new Department() {Id = 1, Name="IT" },
                    new Department() {Id = 2, Name="HR" },
                    new Department() {Id = 3, Name="Manager" },
            };

            return ListDepartments;
        }
    }
}
Modifying Home Controller:

Next, modify the Home Controller as follows.

using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;

namespace HTML_HELPER.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            Company company = new Company();
            //company.SelectedDepartment = 2;
            return View(company);
        }

        [HttpPost]
        public string Index(Company company)
        {
            if (company.SelectedDepartment <= 0)
            {
                return "You did not select any department";
            }
            else
            {
                return "You selected department with ID = " + company.SelectedDepartment;
            }
        }
    }
}
Modifying Index Views:

Next, modify the Index.cshtml view as follows.

@model HTML_HELPER.Models.Company
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
    foreach (var department in Model.Departments())
    {
        @Html.RadioButtonFor(m => m.SelectedDepartment, department.Id)
        @department.Name
    }
    <br />
    <br />
    <input type="submit" value="Submit" />
}

In the above example, the first parameter in the RadioButtonFor() HTML Helper method is a lambda expression that specifies the model property to be bound with the RadioButton element. We have created radio buttons for the SelectedDepartment property in the above example. So, it generates three <input type=”radio”> elements with id and name set to property name SelectedDepartment. The second parameter is the value that will be sent to the server when the form is submitted.

Note: The RadioButtonFor method takes two arguments: an expression to define the model property and the value of the radio button. The selected value will be bound to the specified model property when the form is submitted.

Testing the Application:

Run the application and inspect the HTML. Once you inspect the HTML, you will see that the following HTML codes are generated by the RadioButton helper method.

<input id="SelectedDepartment" name="SelectedDepartment" type="radio" value="1" />IT
<input id="SelectedDepartment" name="SelectedDepartment" type="radio" value="2" />HR
<input id="SelectedDepartment" name="SelectedDepartment" type="radio" value="3" />Manager

Now click on the Submit button without selecting any department. Notice that you are getting a message stating you have not selected any department. On the other hand, if you select a department and then click on the Submit button, then you will see the selected department ID.

What are the Differences Between Html.RadioButton and Html.RadioButtonFor in ASP.NET Core MVC?

In ASP.NET Core MVC, both Html.RadioButton and Html.RadioButtonFor are HTML Helper methods used to generate radio button inputs in a view. However, they serve slightly different purposes and are used in different contexts. Here are the key differences between Html.RadioButton and Html.RadioButtonFor:

Usage:
  • Html.RadioButton: This HTML Helper method is used when you want to manually generate a set of radio buttons without being directly bound to a model. It allows you to define the name, id, value, and other attributes for the radio button inputs.
  • Html.RadioButtonFor: This HTML Helper method is used when you want to generate radio buttons that are directly bound to a model property. It creates radio button inputs with attributes based on the specified model property and its value.
Binding to Model:
  • Html.RadioButton: This method does not directly bind to a model property. You need to manage the selected value and binding manually.
  • Html.RadioButtonFor: This method is designed to work with model properties. It generates radio buttons that are automatically bound to the specified property. The selected value is bound to the property when the form is submitted.
Syntax: Html.RadioButton:

@Html.RadioButton(“name”, “value”, isChecked)

  • name: The name attribute of the radio button group.
  • value: The value attribute of the radio button.
  • isChecked: A boolean indicating whether the radio button is selected.
Example:
@Html.RadioButton("gender", "male", Model.Gender == "male")
@Html.RadioButton("gender", "female", Model.Gender == "female")
Syntax: Html.RadioButtonFor:

@Html.RadioButtonFor(expression, value)

  • expression: An expression that identifies the model property to which the radio button is bound.
  • value: The value attribute of the radio button.
Example:
@Html.RadioButtonFor(m => m.Gender, "male")
@Html.RadioButtonFor(m => m.Gender, "female")

The Html.RadioButton is suitable for scenarios where you need manual control over the radio button generation and don’t need direct model binding. On the other hand, Html.RadioButtonFor is used when you want to generate radio buttons that are automatically associated with a specific model property, ensuring proper model binding when the form is submitted.

In the next article, I am going to discuss Check Box HTML Helper in ASP.NET Core MVC application. In this article, I explain How to Create a Radio Button using HTML Helper in ASP.NET Core MVC application step by step with examples. I hope you enjoy this Radio Button HTML Helper in ASP.NET Core MVC article.

Leave a Reply

Your email address will not be published. Required fields are marked *