ASP.NET MVC DropDownList Guide
Html.DropDownList() is an HTML helper method in the ASP.NET MVC framework used to generate the HTML code for a dropdown list.
Grammar:
public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)
Description of parameters:
- htmlHelper: represents the current HTML helper object.
- Name: The name represents the dropdown list, and is also the attribute name used for backend model binding.
- selectList: represents a collection of options in a dropdown list, of type IEnumerable
, where SelectListItem represents each option in the dropdown list. - optionLabel: Represents the default option in the dropdown list, it can be an empty string or null.
- htmlAttributes: represents the HTML attributes specified for the dropdown list, which can include the attribute names and their corresponding values.
Original: 请确保您按时完成工作任务。
Paraphrased: Please make sure you complete the tasks on time.
- Create a simple dropdown list in the view.
@Html.DropDownList("Country", ViewBag.CountryList as SelectList)
- Country: The name of the dropdown list, which is also the corresponding attribute name in the backend model.
- ViewBag.CountryList: a collection containing options for a dropdown list.
- Create a dropdown list in the view with default options.
@Html.DropDownList("Country", ViewBag.CountryList as SelectList, "Select a Country")
- “Choose a Country” – Text displayed as the default option.
- Create a dropdown list in a view with HTML attributes.
@Html.DropDownList("Country", ViewBag.CountryList as SelectList, new { @class = "form-control", onchange = "countryChanged()" })
- Specifying the HTML attributes for class and onchange is done with the code: new { @class = “form-control”, onchange = “countryChanged()” }.
- Provide a collection of options for the dropdown list in the backend controller.
ViewBag.CountryList = new SelectList(new List<string> { "USA", "Canada", "UK", "Australia" });
- Pass the collection of options to the view using ViewBag.
The above is the basic usage of the Html.DropDownList() method, which can be adjusted and expanded according to our needs.