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 options. Radio buttons are useful when we want the user to select a single option from multiple options, where displaying all possible options simultaneously is preferable for a quick decision. The following are some of the key characteristics of Radio Button in Web Applications:

  • Mutually Exclusive: Radio buttons are designed to be mutually exclusive, meaning that only one option can be selected. When a user selects a new option, any previously selected option within the same group becomes deselected.
  • Grouping: Radio buttons are grouped using the same name attribute in HTML to enforce mutual exclusivity. This ensures that they behave as a single unit, and only one option can be selected within that group.
  • 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 or choosing a payment method.

The following is an 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 we want to manually specify the form field’s name, 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.

Example to Understand RadioButton HTML Helper Method in ASP.NET MVC:

The RadioButton HTML helper in ASP.NET Core MVC generates HTML radio button inputs within a view. This helper is useful when you want to present users with mutually exclusive options and let them choose one. Three overloaded versions are available for the RadioButton() HTML Helper method. They are as follows:

RadioButton HTML Helper Method in ASP.NET MVC

Parameters:
  • name: The name of the radio button group used to distinguish it from other inputs. Radio buttons with the same name will be grouped, allowing only one of them to be selected.
  • value: The value assigned to the radio button.
  • isChecked: A Boolean value indicating whether the radio button should be checked by default.
  • htmlAttributes: Additional HTML attributes to apply to the radio button (optional), such as style or class.
Modifying Home Controller:

First, modify the Home Controller as follows:

using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}
Modifying the Index View:

Next, modify the Index View as follows. The following code is self-explained, so please read the comment lines for a better understanding.

@{
    // Setting the title of the page to "Home Page"
    ViewData["Title"] = "Home Page";
}

<div class="form-group">
    <!-- Wraps the radio button and its descriptive text (Male) in a label for better accessibility -->
    <label class="form-check-label">
        @Html.RadioButton("Gender", "Male", false, new { @class = "form-check-input" })
        <!--
        Renders a radio button input element:
        - "Gender" is the name attribute, grouping this with other inputs with the same name so only one can be selected.
        - "Male" is the value attribute, which will be the value sent when this radio button is selected.
        - false indicates that this radio button is not checked by default.
        - Adds Bootstrap's "form-check-input" class for styling consistency with Bootstrap forms.
        -->
        Male <!-- Visible label text for the radio button -->
    </label>
</div>
<div class="form-group">
    <!-- Similar label structure for the Female radio button -->
    <label class="form-check-label">
        @Html.RadioButton("Gender", "Female", false, new { @class = "form-check-input" })
        <!--
        Renders a radio button for Female option:
        - Uses the same "Gender" name, ensuring it is part of the same group as the "Male" radio button.
        - "Female" as the value attribute.
        - false indicates this button is also unchecked by default.
        - Uses "form-check-input" class for Bootstrap styling.
        -->
        Female <!-- Visible label text for the radio button -->
    </label>
</div>

Now run the application and inspect the generated HTML; then you will see the following HTML generated for the Radio Buttons:

<div class="form-group">
    <label class="form-check-label">
        <input class="form-check-input" id="Gender" name="Gender" type="radio" value="Male" />
        Male 
    </label>
</div>
<div class="form-group">
    <label class="form-check-label">
        <input class="form-check-input" id="Gender" name="Gender" type="radio" value="Female" />
        Female
    </label>
</div>
What is RadioButtonFor HTML Helper in ASP.NET Core MVC?

The RadioButtonFor HTML Helper in ASP.NET Core MVC creates a strongly typed radio button input element that is bound to a property of the model passed to the view. It is similar to the RadioButton helper but offers the advantage of model binding, which simplifies form submission and validation when working with a strongly typed view model. The following is the Syntax of the RadioButtonFor Helper method.
@Html.RadioButtonFor(Expression<Func<TModel, TValue>> expression, object value, object htmlAttributes)

Parameters:
  • expression: An expression that identifies the model property to which the radio button is bound. This expression ensures that the radio button reflects the value of the model property and that any changes made in the form are updated in the model.
  • value: The value of the radio button, i.e., what will be sent to the server when this button is selected.
  • htmlAttributes: An object that contains additional HTML attributes (e.g., classes, styles, IDs) that can be applied to the radio button for customization.
Example to Understand RadioButtonFor HTML Helper in ASP.NET Core MVC

Let’s understand RadioButtonFor HTML Helper in ASP.NET Core MVC with an example. First, create two models. Right-click on the Models folder and add two class files named Company.cs and Department.cs. Once you create the class files, copy and paste the following code.

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. In the below 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 sent to the server when the form is submitted.

@model HTML_HELPER.Models.Company
@{
    ViewBag.Title = "Index";
}

<h2>Home Page</h2>

@using (Html.BeginForm())
{
    <div class="form-group">
        @foreach (var department in Model.Departments())
        {
            <div class="form-check">
                <label class="form-check-label">
                    @Html.RadioButtonFor(m => m.SelectedDepartment, department.Id, new { @class = "form-check-input" })
                    @department.Name
                </label>
            </div>
        }
    </div>

    <div class="form-group">
        <input type="submit" value="Submit" class="btn btn-primary" />
    </div>
}
Understanding Bootstrap Classes used in the above code:
  • form-group: Wrapping the entire form content in Bootstrap’s form-group to ensure proper spacing and layout for form elements.
  • form-check: Each radio button and label pair is wrapped inside a form-check div, a Bootstrap class specifically for checkboxes and radio buttons.
  • form-check-input: This Bootstrap class is applied to the radio buttons to style them consistently.
  • form-check-label: The label that accompanies the radio button is styled with this class to align it properly with the radio button.
  • Submit button: The submit button is styled with Bootstrap’s btn btn-primary classes to make it look like a primary action button.
Testing the Application:

Now, run the application and click the Submit button without selecting any department. You will receive a message stating that you have not selected any department. However, if you choose a department and click 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, both Html.RadioButton and Html.RadioButtonFor are HTML helper methods used to create radio button inputs on a form, but they are used in slightly different contexts and have different benefits. Here’s a breakdown of the key differences between these two methods:

Type-Safety and Strong Typing
  • Html.RadioButtonFor: This method is strongly typed and directly tied to a model property. It uses lambda expressions to refer to model properties, ensuring compile-time checking. This reduces errors due to typos or type mismatches because references are checked at compile time.
  • Html.RadioButton: This method is not strongly typed and relies on string literals to specify which model property it is associated with. Since these are only checked at runtime, there is a greater risk of runtime errors due to misspellings or incorrect property names.
Model Binding
  • Html.RadioButtonFor: Since it’s strongly typed, it’s automatically bound to the model property specified in the lambda expression. This ensures that the model binding is straightforward during form submissions and less prone to errors.
  • Html.RadioButton: To bind correctly on form submissions, manually ensure that the name attribute matches the model property name. Mistakes in the “propertyName” can lead to binding errors.
Default State Handling
  • Html.RadioButton: We need to explicitly specify whether the radio button should be selected or not by passing a Boolean value. For example, false indicates that the radio button is not checked by default.
  • Html.RadioButtonFor: Automatically checks the radio button that corresponds to the value of the model’s property. You don’t need to specify the checked state manually, as it is handled based on the model’s data.
Use Cases
  • Html.RadioButtonFor: It is ideal for forms that are strongly model-driven where each input corresponds directly to a model property. It’s especially useful in complex forms, handling multiple fields to maintain consistency and reduce errors.
  • Html.RadioButton: It is useful in simpler scenarios where a form might not be directly or solely bound to a model or where dynamic property names are used. It offers more flexibility in scenarios where model properties might be generated or determined at runtime.

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 *