liveBook · Manning

Option element

As explained in Pro ASP.NET Core 7, Tenth Edition

An option element is an HTML element representing one selectable choice within a select element.

An option element represents one selectable choice inside a select element. Together, they constrain entry to a fixed set of values instead of accepting open-ended input through an input element. section 27.6

Use option elements in two main ways:

  • Define choices directly when the available values are stable, such as Watersports, Soccer, and Chess. section 27.6
  • Generate choices from application data with select and asp-items, passing a sequence of SelectListItem objects or adapting data through SelectList. section 27.7
  • Let the SelectTagHelper associate the select with a model property while the OptionTagHelper selects the matching option. section 27.6

Reflecting the selected model value

A product whose CategoryId is 2 can render an option such as <option value="2" selected="selected">Soccer</option>. The generated HTML marks the option corresponding to the model value, so the form displays the product’s current category. section 27.6

Creating a related category

A category select can include an option with value -1 labeled Create New Category.... JavaScript can reveal a separate category editor when that option is chosen, allowing the new category to be saved before the product is validated. section 31.4.1

Table 27.8 The built-in tag helper attributes for select elements (view table figure)

Name

Description

asp-for

This attribute is used to specify the view or page model property that the select element represents.

asp-items

This attribute is used to specify a source of values for the option elements contained within the select element.

Use the select tag helper attribute reference to compare asp-for, which identifies the represented model property, with asp-items, which supplies option values. section 27.6

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains static and database-generated options, selected-value rendering, and helper coordination without detailing the helper implementations.
Examples
Uses product categories, selected Soccer markup, database-backed categories, and a Create New Category option.
What it assumes
Assumes familiarity with HTML select controls and model properties while contrasting them with open-ended input elements.
What you can do after
Apply it via ASP.NET Core select tag helpers to render fixed or data-backed choices and preserve the model’s selected value.
How it connects
Connects option elements with select elements, input elements, model binding, SelectTagHelper, OptionTagHelper, SelectList, and Entity Framework Core.

Also explained in

Compare how 2 books explain option element →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.