DropDownList HTML Helper in ASP.NET MVC
DropDownList HTML Helper in ASP.NET MVC
- What is a DropDownList?
- Understanding DropDownList() HTML Helper Method in ASP.NET MVC.
- How to set the Dropdown list values from the database in the ASP.NET MVC Application?
- How to use Enum to set the Dropdown list values in MVC?
- 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.
- DropDownList() Helper Method
- 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.
Parameters:
- htmlHelper: The HTML helper instance that this method extends.
- name: The name of the form field to return.
- selectList: A collection of System.Web.Mvc.SelectListItem objects that are used to populate the drop-down list.
- optionLabel: The text for a default empty item. This parameter can be null.
- 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 < 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 ListListDepartments = new List() < new Department() , new Department() , new Department() , >; // 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() < Listitems = new List(); 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, “Select Department”,new < @class = “form-control”>)
If you inspect the dropdown list then it will generate the below code
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
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
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 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 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.
P arameters:
- htmlHelper: The HTML helper instance that this method extends.
- expression: An expression that identifies the object that contains the properties to display.
- selectList: A collection of System.Web.Mvc.SelectListItem objects that are used to populate the drop-down list.
- optionLabel: The text for a default empty item. This parameter can be null.
- htmlAttributes: An object that contains the HTML attributes to set for the element.
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 ListListDepartments = new List() < new Department() , new Department() , new Department() , >; 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.
Create DropdownList in ASP.NET MVC
Learn how to generate the dropdownlist HTML control using the HtmlHelper in a razor view.
The HtmlHelper class includes two extension methods to generate the control in a razor view: DropDownListFor() and DropDownList() .
We will use the following Student model class and Gender enum.
public class Student < public int StudentId < get; set; >public string StudentName < get; set; >public Gender StudentGender < get; set; >> public enum Gender
Html.DropDownListFor()
The Html.DropDownListFor extension method is a strongly typed extension method generates element for the property specified using a lambda expression.
Visit docs.microsoft.com to know all the overloads of DropDownListFor method.
The following example creates dropdown list for the above StudentGender property.
@using MyMVCApp.Models @model Student @Html.DropDownListFor(m => m.StudentGender, new SelectList(Enum.GetValues(typeof(Gender))), "Select Gender")
select class="form-control" id="StudentGender" name="StudentGender"> option>Select Genderoption> option>Maleoption> option>Femaleoption> select>
In the above example, the first parameter in DropDownListFor() method is a lambda expression that specifies the model property to be bind with the select element. We have specified the StudentGender property. The second parameter specifies the items to show into a dropdown list using SelectList object. The third parameter is optional, which will be the first item of dropdownlist. So now, it generates control with two list items — Male & Female, as shown below.
Html.DropDownList()
The Html.DropDownList() method generates a element with specified name, list items and html attributes.
Visit docs.microsoft.com to know all the overloads of DropDownList() method.
@using MyMVCApp.Models @model Student @Html.DropDownList("StudentGender", new SelectList(Enum.GetValues(typeof(Gender))), "Select Gender", new < @class = "form-control" >)
select class="form-control" id="StudentGender" name="StudentGender"> option>Select Genderoption> option>Maleoption> option>Femaleoption> select>
In the above example, the first parameter is a property name for which we want to display list items. The second parameter is a list of values to be included in the dropdown list. We have used Enum methods to get the Gender values. The third parameter is a label, which will be the first list item, and the fourth parameter is for HTML attributes like CSS to be applied on the dropdownlist.