Back to: ASP.NET Core Tutorials For Beginners and Professionals
DropDownList HTML Helper in ASP.NET Core MVC
In this article, I am going to discuss the DropDownList HTML Helper Method in ASP.NET Core MVC Application with Examples. Please read our previous article, where we discussed the TextArea HTML Helper in ASP.NET Core MVC Application.
DropDownList HTML Helper in ASP.NET Core MVC
In ASP.NET Core MVC, the DropDownList HTML Helper generates an <select> element representing a dropdown list in an HTML form. This helper simplifies the process of creating dropdown lists by automatically generating the HTML markup for us.
What is a DropDownList?
A DropDownList in an ASP.NET Core MVC application is nothing but a collection of SelectListItem objects. Depending on your business requirement, you may either hard code the values or you may retrieve the values from a database table. In this article, I am going to discuss both approaches. First, we will discuss creating the DropDownList using the hard-coded values and then see how to create the DropDownList with the values from a database.
The HtmlHelper class in MVC provides two extension methods to generate the <select> element in a view. They are
- DropDownList() Helper Method
- DropDownListFor() Helper Method
Example to Understand DropDownList HTML Helper Method in ASP.NET Core
The following code will generate a department dropdown list. The first item in the drop-down list will be “Select Department”. Here, we have used the Selected property to true for the IT element, so elements will be selected by default when the page loads.
@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.
How do you set the Dropdown list values from the database in the ASP.NET Core MVC?
Most of the time, or in real-time applications, we generally get the data from a database. To understand this, let’s create a Department Class and then populate the values within the controller. First, add a class file with the name Department.cs within the Models folder and then copy and paste the following code into it.
namespace HTML_HELPER.Models { public class Department { public int Id { get; set; } public string Name { get; set; } = null!; } }
Then, modify the Home Controller as follows. To pass the list of Departments from the controller action method to the Index View, we are storing the list of departments in the ViewBag.
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; namespace HTML_HELPER.Controllers { public class HomeController : 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(); } } }
Or you can also do the same thing in the following way.
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; namespace HTML_HELPER.Controllers { public class HomeController : Controller { public ActionResult Index() { List<SelectListItem> items = new List<SelectListItem>() { new SelectListItem { Text = "IT", Value = "1" }, new SelectListItem { Text = "HR", Value = "2" }, new SelectListItem { Text = "Payroll", Value = "2" } }; ViewBag.Departments = items; return View(); } } }
Next, modify the Index.cshtml view as follows. In the Index view, access the Department list from ViewBag.
@Html.DropDownList("Departments", @ViewBag.Departments as List<SelectListItem>, "Select Department", new { @class = "form-control"})
In the above example, the first parameter is the property name for which we want to display the list of items. The second parameter is the list of values that are going to be displayed within the DropDownList. Here, we have used the ViewBag mechanism to get the department values. The third parameter is the label, which is nothing but the first item in the drop-down list, and the fourth parameter is for the HTML attributes like CSS to be applied on the dropdown list.
If you inspect the dropdown list, it will generate the code below.
<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>
How to use Enum to set the Dropdown list values in ASP.NET Core MVC Application?
Let’s see how to use Enum to set the Dropdown list values. In this example, we are going to set the Gender Values from the enum. So, create a class file with the name Gender.cs and then add the following Gender enum.
namespace HTML_HELPER.Models { public enum Gender { Male, Female } }
Copy and paste the following code into the index view.
@using HTML_HELPER.Models @{ Layout = null; } @Html.DropDownList("EmployeeGender", new SelectList(Enum.GetValues(typeof(Gender))), "Select Gender", new { @class = "form-control" })
In the above example, the first parameter is the property name for which we want to display the list items. The second parameter is the list of values, which will be displayed in the drop-down list. We have used Enum methods to get Gender enum values. The third parameter is the label, which will be the first list item in the drop-down list, and the fourth parameter is for the HTML attributes like CSS to be applied on the dropdown list.
When we run the application, it will generate the following HTML
<select class="form-control" id="EmployeeGender" name="EmployeeGender"><option value="">Select Gender</option> <option>Male</option> <option>Female</option> </select>
DropDownListFor HTML Helper in ASP.NET Core MVC Application:
The DropDownListFor() HTML Helper method in ASP.NET Core MVC is a strongly typed extension method. This helper method generates an <select> element for the property that needs to be specified by using a lambda expression. The DropDownListFor() HTML Helper method will bind a specified property of a model object to the drop-down list control. As a result, it automatically displays the list of items in the drop-down list.
Example to Understand DropDownListFor HTML Helper Method
We are going to use the following models to understand the DropDownListFor HTML Helper in ASP.NET Core MVC Application.
Employee.cs
namespace HTML_HELPER.Models { public class Employee { public int EmployeeId { get; set; } public string EmployeeName { get; set; } = null!; public string Gender { get; set; } = null!; public int DepartmentID { get; set; } } }
Department.cs
namespace HTML_HELPER.Models { public class Department { public int Id { get; set; } public string Name { get; set; } = null!; } }
Gender.cs
namespace HTML_HELPER.Models { public enum Gender { Male, Female } }
Modify the HomeController as shown below.
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; namespace HTML_HELPER.Controllers { public class HomeController : Controller { public ActionResult Index() { //Let’s 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; //let’s create one employee Employee emp = new Employee() { EmployeeId = 1, EmployeeName = "Pranaya", Gender = "Male", DepartmentID = 2 }; //Pass that employee to the view return View(emp); } } }
Modify the Index.cshtml file as shown below:
@using HTML_HELPER.Models @model Employee @{ ViewData["Title"] = "Home Page"; Layout = null; } @Html.DropDownListFor(emp => emp.Gender, new SelectList(Enum.GetValues(typeof(Gender))), "Select Gender", new { @class = "form-control" }) @Html.DropDownListFor(emp => emp.DepartmentID, new SelectList(ViewBag.Departments, "Id", "Name"), "Select Department", new { @class = "form-control" })
In the above example, the first parameter in the DropDownListFor() HTML Helper method is a lambda expression that specifies the model property to be bound with the select element. We have specified the Gender property of the enum type and DepartmentID property. The second parameter specifies the items to show in the dropdown list using SelectList. The third parameter is the option Label, which will be the first item of the drop-down list.
Using DropDownList, if you want to show the selected Department of that particular employee, then you need to use the following code.
@Html.DropDownList("DepartmentID", new SelectList(ViewBag.Departments, "Id", "Name", Model.DepartmentID), "Select Department", new { @class = "form-control" })
What are the Differences Between Html.DropDownListFor and Html.DropDownList in ASP.NET Core MVC?
In ASP.NET Core MVC, both Html.DropDownListFor and Html.DropDownList are HTML Helper methods used to generate dropdown lists, but they have differences in terms of their usage and capabilities.
- Html.DropDownListFor: Html.DropDownListFor is a strongly typed HTML Helper method that generates a dropdown list based on a model property. It’s typically used when you want to bind the selected value of the dropdown list to a property on your model.
- Html.DropDownList: Html.DropDownList is a more general HTML Helper method that generates a dropdown list without being tied to a specific model property. It’s often used when you need more control over the generated HTML or when you’re not directly binding the selected value to a model property.
Key Differences Between Html.DropDownListFor and Html.DropDownList:
- Strongly Typed vs. General: Html.DropDownListFor is strongly typed and binds the dropdown selection to a specific model property, while Html.DropDownList is more general and doesn’t require a direct model property binding.
- Usage: Use Html.DropDownListFor when you want to associate the selected value with a model property, and use Html.DropDownList when you need more flexibility in naming or handling the dropdown.
- Model Binding: Html.DropDownListFor provides a more direct way to bind the selected value to a model property, which can be convenient when dealing with form submissions.
- Control: Html.DropDownList gives you more control over the generated HTML and is suitable when you need customization beyond the standard model property binding.
Choose the appropriate method based on your specific requirements if you want to directly bind the dropdown selection to a model property, Html.DropDownListFor is often the preferred choice. If you need more flexibility in naming or HTML generation, Html.DropDownList might be a better fit.
In the next article, I am going to discuss Radio Button HTML Helper in ASP.NET Core MVC application. In this article, I explain How to Create DropDownList using HTML Helper in ASP.NET Core MVC application step by step with examples. I hope you enjoy this DropDownList HTML Helper in ASP.NET Core MVC article.