I will explain the DropDownList HTML Helper in ASP.NET MVC applications. Before proceeding, I recommend reading our previous article, which covered how to create TextBox and TextArea using HTML Helper methods in MVC. To generate a DropDownList in an ASP.NET MVC application, we use the DropDownList HTML Helper method. Throughout this article, we will cover the following key points.
In ASP.NET MVC, a DropDownList is an HTML helper used to generate a <select> element in a view. It allows users to select a single option from a list of predefined values. The DropDownList HTML Helper simplifies binding data from a model or database, making it easy to populate dropdown options dynamically.
MVC provides two main helper methods to create a DropDownList:
1.DropDownList() – A loosely typed method.
2.DropDownListFor() – A strongly typed method that binds directly to a model property.
These methods help create user-friendly dropdowns while maintaining a clean and efficient code structure in an MVC application.
The code below creates a department dropdown list, with "Select Department" as the first option.
@Html.DropDownList("Departments", new List<selectlistitem>
{
new SelectListItem { Text = "IT", Value = "1", Selected=true},
new SelectListItem { Text = "HR", Value = "2"},
new SelectListItem { Text = "Payroll", Value = "3"}
}, "Select Department")
The downside of hard-coding the DropDownList value within the code itself is that if we have to add or remove departments from the DropDownList, the code must be modified every time.
In real-world applications, data is typically retrieved from a database. To demonstrate this, let's create a Department class and populate its values within the controller. Add a Department.cs file inside the Models folder, as shown below.
namespace HTML_HELPER.Models
{
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
}
To send the list of departments from the controller, store them in a ViewBag, as demonstrated below.
namespace HTML_HELPER.Controllers
{
public class EmployeeController : Controller
{
public ActionResult Index()
{
//Get the data from the database
//Here we are creating Department list
List<department> ListDepartments = new List<department>()
{
new Department() {Id = 1, Name="IT" },
new Department() {Id = 2, Name="HR" },
new Department() {Id = 3, Name="Payroll" },
};
// Retrieve departments and build SelectList
ViewBag.Departments = new SelectList(ListDepartments, "Id", "Name");
return View();
}
}
}
Alternatively, you can achieve the same result using the following approach.
namespace HTML_HELPER.Controllers
{
public class EmployeeController : Controller
{
public ActionResult Index()
{
List<selectlistitem> items = new List<selectlistitem>();
items.Add(new SelectListItem { Text = "IT", Value = "1" });
items.Add(new SelectListItem { Text = "HR", Value = "2" });
items.Add(new SelectListItem { Text = "Payroll", Value = "2" });
ViewBag.Departments = items;
return View();
}
}
}
Now, in the Index view, retrieve the department list from ViewBag, as shown below.
@Html.DropDownList(“Departments”, @ViewBag.Departments as List<selectlistitem>, “Select Department”,new { @class = “form-control”})
If you examine the dropdown list, it will produce the following code.
<select class="form-control" id="Departments" name="Departments">
<option value="">Select Department</option>
<option value="1">IT</option>
<option value="2">HR</option>
<option value="2">Payroll</option>
</select>
In the given example, the first parameter represents the property name associated with the list of items to be displayed. The second parameter contains the collection of values that will populate the DropDownList. Here, the ViewBag mechanism is used to retrieve the department values. The third parameter specifies the label, which serves as the initial item in the dropdown list. The fourth parameter is used for defining HTML attributes, such as applying CSS styles to the dropdown.
Let's explore how to utilize an Enum to populate the values in a Dropdown list. In this example, we will assign gender values using an Enum.
public enum Gender
{
Male,
Female
}
Insert the following code into the Index view.
@using HTML_HELPER.Models
@Html.DropDownList("EmployeeGender",
new SelectList(Enum.GetValues(typeof(Gender))),
"Select Gender",
new { @class = "form-control" })
When we execute the application, it will produce the following HTML.
<select class="form-control" id="EmployeeGender" name="EmployeeGender">
<option value="">Select Gender</option>
<option>Male</option>
<option>Female</option>
</select>
In the example above, the first parameter represents the property name associated with the list of items to be displayed. The second parameter is a collection of values that will appear in the drop-down list. We have used Enum methods to retrieve the gender values from the Enum. The third parameter defines the label, which serves as the first item in the drop-down list, while the fourth parameter is used for specifying HTML attributes, such as applying CSS styles to the dropdown.
We will use the following models to explore the functionality of the DropDownListFor HTML Helper.
Employee.cs
namespace HTML_HELPER.Models
{
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string Gender { get; set; }
public int DepartmentID { get; set; }
}
}
Department.cs
namespace HTML_HELPER.Models
{
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
public enum Gender
{
Male,
Female
}
}
Update the EmployeeController as demonstrated below.
namespace HTML_HELPER.Controllers
{
public class EmployeeController : Controller
{
public ActionResult Index()
{
//Lets create list department for dropdownlist
List<department> ListDepartments = new List<department>()
{
new Department() {Id = 1, Name="IT" },
new Department() {Id = 2, Name="HR" },
new Department() {Id = 3, Name="Payroll" },
};
ViewBag.Departments = ListDepartments;
//lets create one employee
Employee emp = new Employee()
{
EmployeeId = 1,
EmployeeName = "Anam",
Gender = "Female",
DepartmentID = 1
};
//Pass that employee to the view
return View(emp);
}
}
}
Update the Index.cshtml file as shown below.
@using HTML_HELPER.Models
@model Employee
@Html.DropDownListFor(emp => emp.Gender,
new SelectList(Enum.GetValues(typeof(Gender))),
"Select Gender",
new { @class = "form-control" })
@Html.DropDownList("Department",
new SelectList(ViewBag.Departments, "Id", "Name"),
"Select Department",
new { @class = "form-control" })
Alternatively, if you wish to display the selected department for that specific employee, you can use the following code.
@Html.DropDownListFor(emp => emp.DepartmentID,
new SelectList(ViewBag.Departments, "Id", "Name"),
"Select Department",
new { @class = "form-control" })
@Html.DropDownList("DepartmentID",
new SelectList(ViewBag.Departments, "Id", "Name", Model.DepartmentID),
"Select Department",
new { @class = "form-control" })
In the example above, the first parameter in the DropDownListFor() HTML Helper method is a lambda expression that defines the model property to be linked with the select element. We have used the Gender property of the enum type and the DepartmentID property. The second parameter indicates the items to be displayed in the dropdown list, utilizing SelectList. The third parameter represents the option label, which will appear as the first item in the drop-down list.