SelectListItem represents one option in an ASP.NET Core select list. Its Value supplies the submitted value, Text supplies the displayed label, and the collection order controls the option order. The Select Tag Helper expects an IEnumerable<SelectListItem> for asp-items. section 18.2.4
Use SelectListItem objects to prepare select-list data separately from the property that receives submitted values.
- Store the available options in an IEnumerable<SelectListItem> property, commonly populated from application data or hardcoded values. section 18.2.4
- Bind a select element with asp-for for the selected value and asp-items for the SelectListItem collection. section 18.2.4
- Associate items with SelectListGroup objects through Group to produce grouped optgroup elements. section 18.2.4
- Convert application-specific collections such as List<string> or List<MyClass> before passing them to the Select Tag Helper. section 18.2.4
A language option list
public IEnumerable<SelectListItem> Items { get; set; } = new List<SelectListItem> { new SelectListItem { Value = "csharp", Text = "C#" }, new SelectListItem { Value = "python", Text = "Python" }, new SelectListItem { Value = "js", Text = "JavaScript" } }; <select asp-for="Input.SelectedValue" asp-items="Model.Items"></select> For grouped choices, assign each item a SelectListGroup through its Group property. Add a separate option with an empty value when the form needs an explicit “not selected” choice. section 18.2.4
