DropDownList HTML Helper in ASP.NET MVC

DropDownList HTML Helper in ASP.NET MVC

In this article, I am going to discuss DropDownList HTML Helper in ASP.NET MVC Application. Please read our previous article before proceeding to this article where we discussed How to Create TextBox and TextArea using HTML Helper Methods in MVC Application. In order to generate a DropDownList in ASP.NET MVC Application, we need to use the DropDownList HTML Helper Method. As part of this article, we are going to discuss the following pointers.

  1. What is a DropDownList?
  2. Understanding DropDownList() HTML Helper Method in ASP.NET MVC.
  3. How to set the Dropdown list values from the database in the ASP.NET MVC Application?
  4. How to use Enum to set the Dropdown list values in MVC?
  5. Understanding DropDownListFor HTML Helper in ASP.NET MVC Application.
What is a DropDownList?

A DropDownList in ASP.NET 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 value then we will see how to create the DropDownList with the values coming from a database.

The HtmlHelper class in MVC provides two extension methods to generate the <select> element in a view. They are

  1. DropDownList() Helper Method
  2. DropDownListFor() Helper Method
DropDownList() HTML Helper Method in ASP.NET MVC:

There are 8 overloaded versions available for the DropDownList HTML Helper method as shown in the below image.

DropDownList HTML Helper Method in ASP.NET MVC

Parameters:
  1. htmlHelper: The HTML helper instance that this method extends.
  2. name: The name of the form field to return.
  3. selectList: A collection of System.Web.Mvc.SelectListItem objects that are used to populate the drop-down list.
  4. optionLabel: The text for a default empty item. This parameter can be null.
  5. htmlAttributes: An object that contains the HTML attributes to set for the element.

Returns: Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, an option label, and the specified HTML attributes.

Example: DropDownList HTML Helper Method in ASP.NET MVC Application

The following code will generate a department dropdown list. The first item in the drop-down list will be “Select Department”.

@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 then the code needs to be modified each and every time. 

How to set the Dropdown list values from the database in the ASP.NET MVC Application?

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 as shown below. Add Department.cs class file in Models folder as shown below.

namespace HTML_HELPER.Models
{
    public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

To pass the list of Departments from the controller store them in a “ViewBag” as shown 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();
        }
    }
}

Or you can also do the same thing in the following way

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 access the Department list from “ViewBag” as shown below

@Html.DropDownList(“Departments”, @ViewBag.Departments as List<SelectListItem>, “Select Department”,new { @class = “form-control”})

If you inspect the dropdown list then it will generate the below 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 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 which 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.

How to use Enum to set the Dropdown list values in ASP.NET 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.

In Department.cs file add the following enum
public enum Gender
{
    Male,
    Female
}

Copy and paste the following code in the index view

@using HTML_HELPER.Models

@Html.DropDownList("EmployeeGender",
                    new SelectList(Enum.GetValues(typeof(Gender))),
                    "Select Gender",
                    new { @class = "form-control" })

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>

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 is going to 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.

Please note that you can add @using HTML_HELPER.Models namespace into the <namespaces> section in web.config which is present within the Views folder instead of using @using to include the namespace in all the views.

DropDownListFor HTML Helper in ASP.NET MVC Application:

The DropDownListFor() HTML Helper method is a strongly typed extension method. This helper method is used to generate an <select> element for the property which is needed 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 items in the drop-down list. There are 6 overloaded versions available for the DropDownListFor HTML Helper method in ASP.NET MVC Framework as shown in the below image.

DropDownListFor HTML Helper Method in ASP.NET MVC

Parameters:
  1. htmlHelper: The HTML helper instance that this method extends.
  2. expression: An expression that identifies the object that contains the properties to display.
  3. selectList: A collection of System.Web.Mvc.SelectListItem objects that are used to populate the drop-down list.
  4. optionLabel: The text for a default empty item. This parameter can be null.
  5. htmlAttributes: An object that contains the HTML attributes to set for the element.

Type parameters:

  1. TModel: The type of model.
  2. TProperty: The type of value.

Returns: Returns an HTML select element for each property in the object that is represented by the specified expression using the specified list items, option label, and HTML attributes.

Example: DropDownListFor HTML Helper Method in ASP.NET MVC Application

We are going to use the following models to understand 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
    }
}

Modify the EmployeeController as shown 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 = "Pranaya",
                Gender = "Male",
                DepartmentID = 1
            };

            //Pass that employee to the view
            return View(emp);
        }
    }
}

Modify 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" })

Or if you want to show the selected Department of that particular employee then copy and paste 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 above example, the first parameter in DropDownListFor() HTML Helper method is a lambda expression that specifies the model property to be bind with the select element. We have specified Gender property of enum type and DepartmentID property. The second parameter specifies the items to show into the dropdown list using SelectList. The third parameter is the option Label which will be the first item of the drop-down list.

In the next article, I am going to discuss Radio button HTML Helper in ASP.NET MVC application. Here, in this article, I try to explain How to Create DropDownList using HTML Helper in ASP.NET MVC application step by step with examples. I hope this DropDownList HTML Helper in ASP.NET MVC article will help you with your need.