Html DropDownListFor set selected value

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.

Example: Student Model
Copy
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 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.

Example: Html.DropDownListFor[] in Razor View
Copy
@using MyMVCApp.Models @model Student @Html.DropDownListFor[m => m.StudentGender, new SelectList[Enum.GetValues[typeof[Gender]]], "Select Gender"]
Html Result:
Select Gender Male Female

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.

ADVERTISEMENT

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.

Example: Html.DropDownList[] in Razor View
Copy
@using MyMVCApp.Models @model Student @Html.DropDownList["StudentGender", new SelectList[Enum.GetValues[typeof[Gender]]], "Select Gender", new { @class = "form-control" }]
Html Result:
Select Gender Male Female

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.

Video liên quan

Chủ Đề