RadioButton HTML Helper in ASP.NET Core MVC

RadioButton HTML Helper in ASP.NET Core MVC

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

What is RadioButton in Web Application?

A Radio Button in web applications is an input element that allows users to select one option from a predefined set of choices. Radio buttons are particularly useful when you want the user to pick a single option from multiple choices, where displaying all possible options at once is preferable for a quick decision. Radio buttons are typically circular or elliptical in shape and are used to indicate the user’s selection. Here’s how a RadioButton works and is typically used in web applications:

  • 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.
  • User Interface: Visually, a radio button appears as a small circle that can be filled or surrounded by a dot when selected. Unselected radio buttons are empty circles.
  • 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 when 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.

Here’s a simple HTML example that demonstrates the use of radio buttons:

<form>
  <p>Select your age range:</p>
  <input type="radio" id="age1" name="age" value="under-18">
  <label for="age1">Under 18</label><br>
  <input type="radio" id="age2" name="age" value="18-30">
  <label for="age2">18-30</label><br>
  <input type="radio" id="age3" name="age" value="31-45">
  <label for="age3">31-45</label><br>
  <input type="radio" id="age4" name="age" value="over-45">
  <label for="age4">Over 45</label>
</form>

In this example, users can select their age range from the provided options. Because all radio buttons share the same name attribute (age), only one of these options can be selected at a time, ensuring a clear and straightforward selection process.

How Do We Create Radio Buttons Using HTML Helper in ASP.NET Core MVC?

To create a Radio button using the HTML Helper Method in the ASP.NET Core MVC Application, we need to use the RadioButton Helper method. In the ASP.NET Core MVC, we can use two different types of RadioButton Helper methods to generate a RadioButton in a Razor view. These two extension methods are RadioButton() and RadioButtonFor().

The Html.RadioButton method is used when you want to specify the name of the form field manually, while Html.RadioButtonFor is used with model properties, providing a strongly typed approach. That means the RadioButton() HTML Helper method is loosely typed, whereas the RadioButtonFor() HTML Helper method is strongly typed.

What is RadioButton HTML Helper in ASP.NET Core MVC?

The @Html.RadioButton() HTML Helper in ASP.NET Core MVC is a server-side helper method used to generate HTML radio button input elements for your web forms. It is part of the ASP.NET Core MVC framework, designed to simplify the process of creating forms and handling form data in web applications. The RadioButton helper is specifically designed to create radio buttons that allow users to select one option from a group of choices.

The basic syntax of the @Html.RadioButton() helper method is as follows: @Html.RadioButton(string name, object value, bool isChecked, object htmlAttributes)

Here,

  • name: The name attribute of the generated radio button, which is used to group together multiple radio buttons. Only one radio button in the same group (i.e., having the same name) can be selected at a time.
  • value: The value attribute for the radio button, which represents the value that will be submitted if this radio button is selected.
  • isChecked: A boolean value indicating whether the radio button should be initially selected (checked) when the page loads.
  • htmlAttributes: An anonymous object that can be used to set HTML attributes for the radio button, such as class, style, id, etc.
Example to Understand 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 loosely typed.

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 remember 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.

What is RadioButtonFor HTML Helper in ASP.NET Core MVC?

The RadioButtonFor() HTML helper in ASP.NET Core MVC is a server-side helper used to generate an HTML radio button input element for a specified model property. This helper binds a radio button to a model property in your view model, ensuring that the radio button’s state reflects the current value of the model property when rendering the page, and also facilitates the process of updating this property when the form is submitted back to the server.

The RadioButtonFor() helper is strongly typed, meaning it is bound to a specific property of a model passed to your view from a controller. This binding is established through a lambda expression, making it more resistant to errors that can occur due to renaming properties in your model because these changes are often detected at compile time rather than at runtime.

Here’s a basic syntax example of using RadioButtonFor(): @Html.RadioButtonFor(model => model.PropertyName, value, htmlAttributes)

Here,

  • model => model.PropertyName: A lambda expression that specifies the model property to bind to.
  • value: The value to be assigned to the radio button when it is selected.
  • htmlAttributes: (Optional) An object containing HTML attributes to set for the element.
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 named 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. When the form is submitted, the selected value will be bound to the specified model property.

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, 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, the Html.RadioButton and Html.RadioButtonFor helper methods are used to generate radio button controls in a form that is tied to model properties. Understanding the differences between these two methods can help you choose the right one for your scenario. Here’s a breakdown of their main differences:

Purpose and Usage
  • Html.RadioButton: This method is used to create a radio button manually, specifying its name and value directly as parameters. It doesn’t directly bind to a model property. This method is useful when you want full control over the radio button’s value or when the radio button is not directly tied to a model property.
  • Html.RadioButtonFor: This method is strongly typed and used to create a radio button that is automatically bound to a specific property of the model. It uses a lambda expression to specify the model property. This ensures that the radio button is directly tied to a model’s property, making it easier to process form data upon submission.
Syntax

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

  • “name”: The name of the radio button (used for grouping radio buttons together).
  • “value”: The value assigned to the radio button.
  • “isChecked”: Boolean indicating whether the radio button is selected by default.
  • “htmlAttributes”: Object containing HTML attributes for the radio button.

Html.RadioButtonFor Syntax: @Html.RadioButtonFor(model => model.Property, “value”, htmlAttributes)

  • “model => model.Property”: A lambda expression that identifies the model property.
  • “value”: The value assigned to the radio button if it is selected.
  • “htmlAttributes”: Object containing HTML attributes for the radio button.
Model Binding
  • Html.RadioButton: Since it doesn’t bind directly to a model property, you may need to manually handle the retrieval and assignment of values in your controller actions.
  • Html.RadioButtonFor: Provides automatic model binding to the specified property. When the form is submitted, the value of the selected radio button is automatically assigned to the corresponding model property.
Validation
  • Html.RadioButton: This does not automatically participate in model validation because it’s not directly tied to a model property.
  • Html.RadioButtonFor: Supports automatic model validation. If there are validation attributes applied to the model property it is bound to, those validations will automatically be enforced on the client and server side.
Strong Typing and Compile-Time Checking
  • Html.RadioButton: Lacks strong typing since it does not bind directly to a model property. This means there is no compile-time checking for the existence or type of the property it represents, leading to potential runtime errors if mismatches occur.
  • Html.RadioButtonFor: Offers strong typing and compile-time checking, reducing the risk of runtime errors due to property mismatches. This is because it is directly tied to a model property through the lambda expression.
Use Cases
  • Html.RadioButton: Useful in scenarios where the radio buttons do not directly map to model properties or when developing forms that combine data from multiple sources.
  • Html.RadioButtonFor: Ideal for forms that are closely tied to the model structure, especially when using model validation or when the form fields directly correspond to model properties.

Choose Html.RadioButton when you need a radio button not directly tied to a model property or more control over the radio button’s value. On the other hand, Html.RadioButtonFor is more suitable for scenarios where you want to bind radio buttons to model properties directly, taking advantage of model validation and automatic model binding.

In the next article, I will discuss Check Box HTML Helper in ASP.NET Core MVC application. In this article, I explain step-by-step how to create a radio button using HTML Helper in an ASP.NET Core MVC application 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 *