RadioButton HTML Helper in MVC

Creating Radio buttons using RadioButton HTML helper in MVC

In this article, I am going to discuss how to generate radio buttons using RadioButton HTML Helper in MVC application with one example. 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. 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 options.

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

RadioButton() HTML Helper Method:

The Html.RadioButton() HTML Helper method is used to create a radio button element with a specified name, isChecked boolean property and the HTML attributes. The RadioButton Signature is given below:

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

Example:

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 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 Method:

The RadioButtonFor() HTML Helper method is the strongly typed extension method. It is also used to 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. The signature of the RadioButtonFor() HTML Helper Method is given below.

MvcHtmlString RadioButtonFor(<Expression<Func<TModel, TValue>> expression, object value, object htmlAttributes)

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" />
}
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 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.

SUMMARY:

In this article, I try to explain how to generate the radio button list using RadioButton HTML Helper in MVC application step by step with simple examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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