RadioButton HTML Helper in MVC

RadioButton HTML Helper in ASP.NET MVC Application

In this article, I am going to discuss how to generate radio buttons using RadioButton HTML Helper in the ASP.NET MVC application. Please read our previous article before proceeding to this article where we discussed How to Create DropDownList using HTML Helper in ASP.NET MVC applications. As part of this article, we are going to discuss the following pointers.

  1. What is a Radion Button in MVC?
  2. How to generate radio button in ASP.NET MVC?
  3. RadioButton HTML Helper Method in ASP.NET MVC
  4. RadioButtonFor HTML Helper in ASP.NET MVC.
What is a Radion Button in ASP.NET MVC?

A radio button is an element of the graphical user interface (GUI) and its main purpose is to allow a user to select a single item from a predefined list of items.

How to generate radio button in ASP.NET MVC?

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

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

The Html.RadioButton() HTML Helper method in ASP.NET 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 type method. There are 6 overloaded versions of RadioButton HTML Helper methods are available as shown in the below image.

RadioButton HTML Helper in ASP.NET MVC Application

Parameters:
  1. htmlHelper: The HTML helper instance that this method extends.
  2. name: The name of the form field and the System.Web.Mvc.ViewDataDictionary key that is used to look up the value.
  3. value: The value of the selected radio button. The value is retrieved in this order- the System.Web.Mvc.ModelStateDictionary object, the value of this parameter, the System.Web.Mvc.ViewDataDictionary object, and lastly, a value attribute in the html attributes.
  4. isChecked: true to select the radio button; otherwise, false.
  5. htmlAttributes: An object that contains the HTML attributes to set for the element.

Returns: Returns a radio button input element that is used to present mutually exclusive options

 

Example to understand 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 checked=”checked” 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 for both the radio button. 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, then the string value “Male” will be assigned to a model property with the name Gender and submitted to the server.

RadioButtonFor HTML Helper in ASP.NET MVC:

The RadioButtonFor HTML Helper method is the strongly typed extension method. It is also used to generate an <input type=”radio”> element in a view.  Here we need to specify the name for the Radion 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. There are 3 overloaded versions of RadioButtonFor HTML Helper methods are available in ASP.NET MVC as shown in the below image.

RadioButtonFor HTML Helper in ASP.NET MVC Application

Parameters:
  1. htmlHelper: The HTML helper instance that this method extends.
  2. expression: An expression that identifies the object that contains the properties to render.
  3. value: The value of the selected radio button. The value is retrieved in this order – the System.Web.Mvc.ModelStateDictionary object, the value of this parameter, the System.Web.Mvc.ViewDataDictionary object, and lastly, a value attribute in the HTML attributes.
  4. htmlAttributes: A dictionary that contains the HTML attributes to set for the element.

Type parameters:

  1. TModel: The type of model.
  2. TProperty: The type of value.

Returns: An HTML input element whose type attribute is set to “radio” for each property in the object that is represented by the specified expression, using the specified HTML attributes.

 

Example: RadioButtonFor HTML Helper in ASP.NET MVC

To understand this let’s create a new project. Right-click on the “Models” folder and then add two class files with the name Company.cs and Department.cs. Once you create the class files then 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 string SelectedDepartment { get; set; }     
        public List<Department> Departments
        {
            get
            {
                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;
            }
        }
    }
}
Creating Controller:

Create a Controller with the name HomeController within the Controllers Folder and then copy and paste the following two action methods in it.

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

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

Right-click on the “Index” action method in “HomeController” and add a view with the name “Index”. Once you create the Index view then copy and paste the following code in it. 

@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" />
}
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 RadionButton helper method.

<input id=”SelectedDepartment” name=”SelectedDepartment” type=”radio” value=”1″>
<input id=”SelectedDepartment” name=”SelectedDepartment” type=”radio” value=”2″>
<input id=”SelectedDepartment” name=”SelectedDepartment” type=”radio” value=”3″>

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. 

In the above example, the first parameter in 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”> element with id and name set to property name – SelectedDepartment. The second parameter is the value which will be sent to the server when the form will be submitted.

In the next example, I am going to discuss How to create CheckBox List using HTML Helper in ASP.NET MVC application. Here, in this article, I try to explain how to generate the radio button using RadioButton HTML Helper in ASP.NET MVC application step by step with simple examples. I hope you enjoy this RadioButton HTML Helper in MVC article.

Leave a Reply

Your email address will not be published.