liveBook · Manning

Select tag helper

As explained in ASP.NET Core in Action, 3e

The Select Tag Helper is an ASP.NET Core Tag Helper that generates HTML select controls and their options from Razor model properties and item collections.

The Select Tag Helper generates HTML select controls and option elements from Razor model properties and item collections. Add asp-for to identify the bound property and asp-items to provide the available options. section 18.2.4

Use the bound property and item collection to choose the select behavior:

  • Bind to a standard property for a drop-down list. section 18.2.4
  • Bind to an IEnumerable property to create a multiselect list box. section 18.6
  • Supply an IEnumerable<SelectListItem>; convert application-specific collections before passing them to the helper. section 18.2.4
  • Assign SelectListGroup objects to item Group properties to generate optgroup elements. section 18.6

Three select styles

public IEnumerable<SelectListItem> Items { get; set; } = new List<SelectListItem>\n{\n new SelectListItem { Value = "csharp", Text = "C#" },\n new SelectListItem { Value = "python", Text = "Python" }\n};\n\n<select asp-for="Input.SelectedValue1" asp-items="Model.Items"></select>\n<select asp-for="Input.SelectedValue2" asp-items="Model.Items" size="4"></select>\n<select asp-for="Input.MultiValues" asp-items="Model.Items"></select>\n\nThe first select is a drop-down, the second is a single-select list box, and the third is multiselect when MultiValues is an IEnumerable property.

For enum options, use Html.GetEnumSelectList<TEnum>() instead of writing the SelectListItem mapping yourself. Add an option with an empty value when the form needs an explicit “not selected” choice; otherwise the select always has a value. section 18.2.4

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains binding, item requirements, grouping, enum mapping, and no-selection options through working Razor examples.
Examples
Uses programming-language options, three select styles, grouped optgroups, enum options, and an explicit not-selected option.
What it assumes
Assumes basic Razor and PageModel properties while teaching SelectListItem collections and IEnumerable multiselect binding.
What you can do after
Builds drop-down, list-box, multiselect, grouped, and enum-backed controls with Razor Tag Helper attributes.
How it connects
Connects Razor, model binding, SelectListItem, SelectListGroup, enums, and HTML select elements.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.