In this write-up, I will explain how to generate radio buttons using the RadioButton HTML Helper in an ASP.NET MVC application. Before continuing, please refer to our previous article where we covered how to create a dropdown list using the HTML Helper in ASP.NET MVC applications. In this article, we will focus on the following key points.
To grasp this concept, let's start by creating a new project. Right-click on the “Models” folder, then add two class files named Company.cs and Department.cs. After creating 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 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;
}
}
}
}
Add a controller named HomeController inside the Controllers folder, and then copy and paste the following two action methods into 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;
}
}
}
}
Right-click on the “Index” action method in “HomeController” and generate a view named “Index.” After creating the Index view, insert the following code.
@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" />
}
Launch the application and examine the HTML. Upon inspection, you will notice that the RadioButton helper method has generated the following HTML code.
Click the “Submit” button without choosing a department. You will see a message indicating that no department has been selected. However, if you pick a department and then press the “Submit” button, the selected department ID will be displayed.