DropDownList HTML Helper in ASP.NET Core MVC

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 that allows 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.

This control is widely used in web forms and applications to save space on the screen, as it only displays the selected item until interacted with. 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.

What is DropDownList HTML Helper in ASP.NET Core MVC?

The DropDownList HTML Helper in ASP.NET Core MVC is a server-side helper method used to dynamically generate a dropdown list (HTML <select> element) on a web page. The DropDownList HTML Helper simplifies the creation of dropdown lists bound to data models or collections, making it easier to select a value from a list of options.

When using the DropDownList HTML Helper, developers can specify the data source for the dropdown list, the field to be displayed to the user, and the field that represents the value of each option. This makes it straightforward to bind the dropdown list to data models or collections, such as lists or enumerations, and to automatically select a value based on the model’s current state.

The DropDownList HTML Helper is used within Razor views and supports various overloads to customize its behavior, including setting the selected item, adding HTML attributes, and grouping options. It is used in conjunction with model binding, allowing for an efficient way to capture user input and update the model state on form submissions.

Example to Understand DropDownList HTML Helper Method in ASP.NET Core

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 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 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 named 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 store 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();
        }
    }
}

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 will 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 drop-down list.

If you inspect the dropdown list, the code below will be generated.

<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 Do We 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 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
    }
}

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() 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 in displaying a list of options the user can select from. The selected value from the drop-down list can then be posted back to the server as part of the model during form submission.

The DropDownListFor() method provides a way to select a single item from a list of items defined in your model or passed through a view model. It is often used in conjunction with the SelectList or SelectListItem classes to populate the drop-down list options. Here’s a basic example of how it might be used in a view:
@Html.DropDownListFor(model => model.SelectedItemId, new SelectList(Model.Items, “Value”, “Text”))
In this example:

  • model => model.SelectedItemId specifies the model property to which the drop-down list is bound. This property holds the selected item’s value.
  • new SelectList(Model.Items, “Value”, “Text”) creates a new SelectList object where Model.Items are the collection of items you want to display in the drop-down. “Value” and “Text” specify the names of the properties in the Model.Items that contain the values and the display texts of the items, respectively.
Example to Understand DropDownListFor HTML Helper Method

We will 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.DropDownList and Html.DropDownListFor helper methods are used to create a <select> dropdown list element in a view. However, they differ in syntax and how they bind data from the model to the view. Understanding these differences can help you choose the right method for your scenario.

Html.DropDownList in ASP.NET Core MVC
  • Syntax: Html.DropDownList(string name, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)
  • Purpose: It creates a dropdown list based on a specified list of items. The name parameter corresponds to the name of the form field and is used to bind the selected value when the form is submitted.
  • Flexibility: It allows for more flexibility in specifying the name of the form field independently from the model properties. This can be useful in scenarios where the dropdown list is not directly tied to a specific model property.
  • Option Label: You can specify an optional label (e.g., “Please select an option”) that is not bound to any value, which can serve as a prompt for the user.
  • Model Binding: As you specify the field name as a string, there’s a loose coupling between the dropdown and the model property. This means you have to be more careful to ensure that the name matches the model property you intend to bind to, especially if refactoring occurs.
Html.DropDownListFor in ASP.NET Core MVC
  • Syntax: Html.DropDownListFor(Expression<Func<TModel, TValue>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)
  • Purpose: This method is strongly typed, meaning it binds the dropdown list directly to a model property. The expression parameter is a lambda expression that identifies the model property the dropdown list is bound to.
  • Type Safety: Since it’s strongly typed, it provides compile-time checking of the property it’s bound to. This reduces the risk of runtime errors due to typos or mismatches between the view and the model.
  • Model Binding: This creates a strong binding between the dropdown and a specific property of the model. The lambda expression clarifies which property the dropdown is associated with, reducing the risk of errors during refactoring and enhancing the clarity of the view’s code.
Key Differences Between Html.DropDownList and Html.DropDownListFor in ASP.NET Core MVC
  • Binding: Html.DropDownList requires manually specifying the name of the form field and does not provide strong typing or compile-time checks. Html.DropDownListFor, on the other hand, binds directly to a model property, ensuring type safety and reducing potential errors.
  • Use Cases: Html.DropDownList might be preferred when the dropdown list does not correspond directly to a model property or when you need to specify a custom name for the form field. Html.DropDownListFor is better suited for standard data entry forms where each dropdown list corresponds directly to a model property.
  • Syntax and Type Safety: Html.DropDownListFor uses a lambda expression to specify the binding property, offering type safety and integration with the model’s properties. Html.DropDownList relies on a string name, which does not offer compile-time error checking.
  • IntelliSense Support: Html.DropDownList has Limited IntelliSense support because the field name is a string literal, so there’s no direct link to the properties of the model. Html.DropDownListFor offers full IntelliSense support due to its strong typing. This can speed up development by providing quick access to model properties and reducing errors caused by typos.

In the next article, I will 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.

Leave a Reply

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