Back to: ASP.NET Core Tutorials For Beginners and Professionals
DropDownList HTML Helper in ASP.NET Core MVC
In this article, I will discuss the DropDownList HTML Helper Method in ASP.NET Core MVC Application with Examples. Please read our previous article discussing the TextArea HTML Helper in ASP.NET Core MVC Application.
What is DropDownList in Web Application?
A DropDownList in a web application is a user interface control allowing users to select a single item from a list of items presented in a dropdown menu. When it is not activated, it shows the currently selected item. When clicked or tapped, it displays a list of options from which the user can select one. The DropDownList is particularly useful for fields that have a fixed set of options, such as:
- Countries
- States or regions within a country
- Categories or types of items
- Settings options that have predefined choices
In HTML, a DropDownList can be created using the <select> element, where each option within the dropdown is defined using an <option> tag. Here’s a basic example:
<select name="country" id="country-dropdown"> <option value="usa">United States</option> <option value="canada">Canada</option> <option value="mexico">Mexico</option> <!-- Additional countries can be added here --> </select>
In this example, the DropDownList allows users to select a country from the list. When a user selects an option, the value of the <select> element (accessible through JavaScript or on the server side after form submission) becomes the value of the selected <option>.
How Do We Create DropDownList using HTML Helper in ASP.NET Core MVC?
To create a DropDownList using the HTML Helper Method in the ASP.NET Core MVC Application, we need to use the DropDownList Helper method. In ASP.NET Core MVC, the DropDownList HTML Helper generates an <select> element representing a dropdown list in an HTML form. We can use two different types of DropDownList Helper methods to generate a textbox in a Razor view. These two extension methods are DropDownList() and DropDownListFor().
The Html.DropDownList method is used when you want to specify the name of the form field manually, while Html.DropDownListFor is used with model properties, providing a strongly typed approach. That means the DropDownList() HTML Helper method is loosely typed, whereas the DropDownList() HTML Helper method is strongly typed.
Example to Understand DropDownList HTML Helper Method in ASP.NET Core
A Drop-down List in an ASP.NET Core MVC application is a collection of SelectListItem objects. Depending on the business requirement, we may either hard code the values or retrieve them from a database table. In this article, I will discuss both approaches. First, we will discuss creating the Drop-down List using the hard-coded values and then see how to create it with the values from a database.
Modifying the Home Controller:
First, modify the Home Controller as follows:
using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } } }
Modifying the Index.cshtml View:
Modify the Index.cshtml view as follows. 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 the “IT” element will be selected by default when the page loads.
@{ ViewData["Title"] = "Home Page"; } <div class="form-group"> <!-- Label for the Departments dropdown --> <label for="Departments" class="form-label">Select Department</label> <!-- Dropdown list with Bootstrap styling --> @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", new { @class = "form-control" }) </div>
Understanding the DropDownList Help Method:
The @Html.DropDownList helper method in ASP.NET Core MVC generates a dropdown list in an HTML form. In our example, we used the following DropDownList Help Method.
Explanation of Parameters
Departments (name Parameter):
This is the name of the form element that will be generated. The name attribute in HTML is used to identify form elements when submitting data. In this case, the form will send the selected department’s value (e.g., “1” for IT, “2” for HR, etc) as the Departments field when submitted.
new List<SelectListItem> {…} (items parameter):
This is the list of options for the dropdown. Each SelectListItem object represents an item in the dropdown with the following properties:
- Text: The text that will be displayed to the user in the dropdown (e.g., “IT”, “HR”, “Payroll”).
- Value: The actual value that will be submitted when the user selects this option (e.g., “1” for IT, “2” for HR, “3” for Payroll).
- Selected: A Boolean value indicates whether this option is selected by default. In our case, “IT” is selected by default because Selected=true is set for the first item.
“Select Department” (optionLabel parameter):
This default text will be shown when no option is selected. This acts as a placeholder for the dropdown and is displayed as an option that cannot be selected. It encourages the user to select an actual department. If the user selects no value, this option will be shown in the dropdown.
new { @class = “form-control” } (htmlAttributes parameter):
This is an anonymous object used to specify HTML attributes for the rendered <select> element. In this case, the form-control class is added to the dropdown to apply Bootstrap styling. You can add other HTML attributes as needed, such as id, data-* attributes, style, etc., by specifying them inside this object.
HTML Output
Now, run the application and access the Index Page. The helper method should generate an HTML <select> element with options corresponding to the list’s items as follows. To see this, please view the page source code in the browser:
<select id="Departments" name="Departments" class="form-control"> <option value="">Select Department</option> <option value="1" selected="selected">IT</option> <option value="2">HR</option> <option value="3">Payroll</option> </select>
Here,
- The id and name attributes are “Departments”.
- The class=”form-control” applies Bootstrap styling.
- The first <option> is the default placeholder text, “Select Department”.
- Each subsequent <option> is generated from the list of items with the appropriate value and text.
- “IT” is selected by default because of Selected=true.
What is the Problem with Hard-Coding DropDownList?
The downside of hard-coding the DropDownList value within the code is that if we add or remove departments from the DropDownList, the code must be modified every time. The following are the limitations of hard-coding the Drop Down List data:
- Repetitive Code: If the dropdown options change frequently, we will have to modify the hardcoded values at every place the dropdown appears in your application. This becomes error-prone and time-consuming, especially in large applications.
- Centralized Management: With hard-coded options, the dropdown values are scattered across multiple views or controllers, making it difficult to manage centrally. If you need to update the dropdown options, you would have to find and edit every instance manually.
- Dynamic Data: Hardcoding means that the options are static, and you cannot dynamically generate them based on external data, such as a database or configuration file. For instance, if departments are stored in a database, you can’t easily pull in new departments without updating the code.
- Don’t Repeat Yourself (DRY): Hardcoding dropdown values violate the DRY principle, a key principle of software development. This principle states that you should avoid duplicating logic or data. By hardcoding dropdown lists, you may end up with repeated code across multiple views, making your application harder to maintain.
- No Data Validation: When dropdown options are hardcoded, we lose the benefit of validation against real-time data. For example, a user might select a department that no longer exists in the database because the dropdown was not updated.
- Data Source Mismatch: If you hardcode values but the actual data (e.g., departments, categories) come from an external source like a database, there’s a risk of mismatches. For instance, if the department names or IDs change in the database, your hardcoded dropdown will no longer reflect the correct data, leading to inconsistencies.
- Hardcoded Values in Views: Having large hardcoded dropdowns in your views can increase the size of the HTML rendered, which may affect page load times, particularly for larger dropdowns or more complex forms.
- Inability to Scale: If you want to support more advanced scenarios like filtering or dynamically preparing the dropdown based on user input or other data sources, hardcoding will limit these possibilities.
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 get the data from a database. To understand this, let’s create a Department Class and then populate the department’s values within the controller. First, add a class file named Department.cs within the Models folder and then copy and paste the following code.
namespace HTML_HELPER.Models { public class Department { public int Id { get; set; } public string Name { get; set; } = null!; } }
Modify Home Controller:
Next, modify the Home Controller as follows. We store the list of departments in the ViewBag, which we will use in the index view. The following code is self-explained, so please read the comment lines for a better understanding.
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class HomeController : Controller { public ActionResult Index() { // Creating a list of departments // Typically, data would be fetched from a database, but here we're manually creating a list of departments for simplicity List<Department> ListDepartments = new List<Department>() { // Adding an IT department to the list with Id=1 and Name="IT" new Department() {Id = 1, Name="IT" }, // Adding an HR department to the list with Id=2 and Name="HR" new Department() {Id = 2, Name="HR" }, // Adding a Payroll department to the list with Id=3 and Name="Payroll" new Department() {Id = 3, Name="Payroll" }, }; // Creating a SelectList for departments, which will be used in the view to generate a dropdown list // The SelectList takes the list of departments as the first argument // The second argument ("Id") specifies the value that will be submitted when a department is selected // The third argument ("Name") specifies the display text for each department in the dropdown list ViewBag.Departments = new SelectList(ListDepartments, "Id", "Name"); // Returning the View to be rendered in the browser. // This will send the model (ViewBag.Departments) to the view for rendering return View(); } } }
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() { // Creating a list of SelectListItem objects to represent options in a dropdown list // Each SelectListItem has 'Text' for display and 'Value' for the submitted data // Selected will set the default selected value in the dropdownlist List<SelectListItem> items = new List<SelectListItem>() { // First dropdown item: Displayed as "IT", with a value of "1" when selected new SelectListItem { Text = "IT", Value = "1", Selected = true }, // Second dropdown item: Displayed as "HR", with a value of "2" when selected new SelectListItem { Text = "HR", Value = "2" }, // Third dropdown item: Displayed as "Payroll", with a value of "3" new SelectListItem { Text = "Payroll", Value = "3" } }; // Assigning the list of SelectListItem objects to the ViewBag with the key "Departments" // This makes the dropdown data accessible to the view when rendering the dropdown list ViewBag.Departments = items; // Returning the view for rendering the HTML content // The ViewBag data (Departments) will be available for use in this view return View(); } } }
Modifying the Index View:
Next, modify the Index.cshtml view as follows. In the Index view, access the Department list from ViewBag.
@{ ViewData["Title"] = "Home Page"; } <div class="form-group"> <!-- Label for the Departments dropdown --> <label for="Departments" class="form-label">Select Department</label> <!-- Dropdown list with Bootstrap styling --> @Html.DropDownList("Departments", @ViewBag.Departments, "Select Department", new { @class = "form-control" }) </div>
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 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 drop-down list.
How Do We Use Enum to Set the Dropdown List Values in the ASP.NET Core MVC Application?
Let’s see how to use Enum to set the Dropdown list values. In this example, we will set the Gender Values from the enum. So, create a class file named Gender.cs and add the following Gender enum.
namespace HTML_HELPER.Models { public enum Gender { Male, Female, Other } }
Modifying the Index View:
Next, modify the Index View as follows. The following HTML code is self-explained. Please read the comment lines for a better understanding.
@{ // Sets the title for the page in the ViewData dictionary, which can be accessed by the layout page or other views to display the page title ViewData["Title"] = "Home Page"; } <div class="form-group"> <!-- This is an HTML label element associated with the select dropdown below. The 'for' attribute must match the 'id' of the select element it labels, improving accessibility --> <label for="Gender" class="form-label">Select Gender</label> <!-- Html.DropDownList is an HTML helper used to generate a dropdown list (select element) --> @Html.DropDownList("Gender", // The first parameter is the name of the form field. It will also be used as the 'name' and 'id' attribute of the resulting HTML select element new SelectList(Enum.GetValues(typeof(Gender))), // The second parameter constructs a new SelectList. It takes the enum values of 'Gender', providing the data source for the dropdown options "Select Gender", // The third parameter is the text to display in the default option, which in this case serves as a prompt to the user to make a selection new { @class = "form-control" } // The fourth parameter is an anonymous object that contains HTML attributes to be added to the select element. Here, it assigns a Bootstrap class for styling ) </div>
Now, run the application and inspect the HTML element, and you will see the following HTML generated for the drop-down list:
<select class="form-control" id="Gender" name="Gender"> <option value="">Select Gender</option> <option>Male</option> <option>Female</option> <option>Other</option> </select>
If you notice, then you will see it is not included in the Value attribute of the Option tag. This is because of the default behavior when using Enum.GetValues() with SelectList. In this case, it will use enum names as both the text and the value in the HTML <option> tags. To specify different values, we need to manually set up the SelectList to use the enum values (i.e., the underlying integer values of the enum) instead of the names. So, modify the Index view as follows:
@{ ViewData["Title"] = "Home Page"; } <div class="form-group"> <!-- Label for the Departments dropdown --> <label for="Gender" class="form-label">Select Gender</label> @Html.DropDownList("Gender", // Name and ID of the <select> element // This SelectList creates the list of options for the dropdown from the Gender enum. // Enum.GetValues(typeof(Gender)) retrieves all the values of the Gender enum (e.g., Male, Female, Other). // .Cast<Gender>() converts these values to the Gender enum type. new SelectList(Enum.GetValues(typeof(Gender)) .Cast<Gender>() // Converts the collection of enum values to Gender type // Select() is a LINQ method that projects each Gender enum value into a new SelectListItem object. // For each Gender enum value, we create a SelectListItem with Text and Value properties. // Text will display the string representation of the enum (e.g., "Male"), and // Value will store the integer value of the enum, cast to a string (e.g., "1" for Male). .Select(e => new SelectListItem { Text = e.ToString(), // The display text for the option (e.g., "Male") Value = ((int)e).ToString() // The value attribute for the option (e.g., "1") }), // "Value" specifies that the dropdown will use the "Value" property of each SelectListItem for the option values. // "Text" specifies that the dropdown will display the "Text" property of each SelectListItem. "Value", "Text"), // The third argument is a string that sets the default placeholder option. // This will create an option with an empty value and the text "Select Gender". "Select Gender", // This anonymous object specifies additional HTML attributes for the <select> element. // @class is a reserved keyword, so it's escaped with @ to define the Bootstrap class "form-control". new { @class = "form-control" }) </div>
This will generate the desired HTML:
<select class="form-control" id="Gender" name="Gender"> <option value="">Select Gender</option> <option value="0">Male</option> <option value="1">Female</option> <option value="2">Other</option> </select>
Example to Understand DropDownListFor HTML Helper Method
The DropDownListFor() is an HTML helper method in ASP.NET Core MVC that is used to generate a <select> element (a drop-down list) for a web page from a model property. This helper is strongly typed, meaning it is bound to a specific model property and helps display a list of options the user can select from. Let us understand this with an example. First, modify the Employee.cs class file as follows:
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; } } }
Modify the HomeController:
Next, modify the Home Controller as follows. In the code below, we created a ViewBag property to hold the list of departments. This ViewBag will render the list of departments on the web page. We have also created an employee object and set the DepartmentID and Gender. While rendering the Gender and Department for the Employee, we need to use this DepartmentID and Gender as the default selected value.
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc; 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); } } }
Modifying Index.cshtml View:
Next, modify the Index View as follows.
@model HTML_HELPER.Models.Employee @{ // Setting the title of the page to "Home Page" ViewData["Title"] = "Home Page"; } <div class="form-group"> <!-- Label for the Gender dropdown --> <label for="Gender" class="form-label">Select Gender</label> <!-- Dropdown list for selecting Gender, using Bootstrap styling The DropDownListFor helper binds the selected value to the "Gender" property of the Employee model The SelectList is created from the Gender enum, generating options based on enum values The first option is a placeholder "Select Gender" The form-control class is used for Bootstrap styling --> @Html.DropDownListFor(emp => emp.Gender, new SelectList(Enum.GetValues(typeof(Gender))), "Select Gender", new { @class = "form-control" }) <!-- Label for the Department dropdown --> <label for="DepartmentID" class="form-label">Select Department</label> <!-- Dropdown list for selecting Department, using Bootstrap styling The DropDownListFor helper binds the selected value to the "DepartmentID" property of the Employee model The SelectList is created from the data stored in ViewBag.Departments, which contains department information The Id of the department is used as the value, and the Name of the department is displayed The first option is a placeholder "Select Department" The form-control class is used for Bootstrap styling --> @Html.DropDownListFor(emp => emp.DepartmentID, new SelectList(ViewBag.Departments, "Id", "Name"), "Select Department", new { @class = "form-control" }) </div>
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 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.
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 create drop-down list elements (<select> tags) in Razor views. However, they differ in how they bind data to the model and how they are used. The following is a breakdown of their differences:
Model Binding
Html.DropDownListFor:
- Strongly typed helper method.
- It is directly tied to a model property and uses that property for data binding.
- When the form is submitted, the selected value in the drop-down list is automatically bound to the corresponding property in the model.
- Ensures type safety and compile-time checking.
Example: @Html.DropDownListFor(model => model.CountryId, new SelectList(ViewBag.Countries, “Value”, “Text”), “Select Country”)
In the example above, the selected value will be bound to the CountryId property of the model.
Html.DropDownList:
- Weakly typed helper method.
- It is not bound to any specific model property, meaning it does not automatically bind the selected value to a property in the model.
- You need to manually specify the name and handle the value binding in the controller.
Example: @Html.DropDownList(“CountryId”, new SelectList(ViewBag.Countries, “Value”, “Text”), “Select Country”)
In this case, the selected value will be bound to the form element with the name CountryId, but you need to manage the binding yourself.
Type Safety
- Html.DropDownListFor: Provides type safety because it is strongly typed and tied to a model property. You’ll get compile-time errors if there are mismatches between the model and view.
- Html.DropDownList: Weakly typed, meaning you lose type safety. Errors might only surface at runtime, such as a mismatch in the name string or improper binding.
Error Handling and Validation
- Html.DropDownListFor: Automatically integrates with ASP.NET Core MVC’s model validation based on data annotations applied to the model properties. This means if there are validation rules like Required, error messages will automatically trigger if the form is submitted without selecting an option.
- Html.DropDownList: Does not directly tie into model validation, so any error handling would need to be managed separately. You have to ensure that validation messages are displayed correctly.
Use Cases
- Html.DropDownListFor: It is typically used when you have a well-defined ViewModel where you know the properties to which the dropdown should bind. It’s ideal when you want to maintain strict type-checking and conformity to the model structure.
- Html.DropDownList: It is used in scenarios where you might not have a specific model defined (e.g., using ViewBag or ViewData to pass data to the view), or where you need the flexibility to specify or change the property name dynamically.
In the next article, I will discuss the Radio Button HTML Helper in an ASP.NET Core MVC application. In this article, I explain how to create a drop-down list using HTML Helper in an ASP.NET Core MVC application with examples. I hope you enjoy this Drop-down List HTML Helper in an ASP.NET Core MVC article.