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 <select>
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
{
Male,
Female
}
Html.DropDownListFor()
The Html.DropDownListFor<TModel,TProperty>
extension method is a strongly typed extension method generates <select>
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 Gender</option>
<option>Male</option>
<option>Female</option>
</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 <select>
control with two list items - Male & Female, as shown below.
Html.DropDownList()
The Html.DropDownList()
method generates a <select>
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 Gender</option>
<option>Male</option>
<option>Female</option>
</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.