DropDownList HTML Helper in MVC

DropDownList HTML Helper in MVC

In this article, I am going to discuss DropDownList HTML Helper in 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 MVC, 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 database in 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 the 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:

We are going to use the following overloaded version of the “DropDownList” HTML helper method which takes three parameters.

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 database in ASP.NET MVC Application?

In 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. 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 MVC application step by step with examples. I hope this article will help you with your need.

Leave a Reply

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