SelectListGroup represents a named group of related options in an ASP.NET Core MVC select list. Assign a group to each SelectListItem through its Group property, and the Select Tag Helper renders grouped options as HTML optgroup elements. section 18.2.4 section 18.6
Group language options
var dynamic = new SelectListGroup { Name = "Dynamic" }; var @static = new SelectListGroup { Name = "Static" }; Items = new List<SelectListItem> { new SelectListItem { Value = "js", Text = "JavaScript", Group = dynamic }, new SelectListItem { Value = "python", Text = "Python", Group = dynamic }, new SelectListItem { Value = "cpp", Text = "C++", Group = @static } }; <select asp-for="SelectedValues" asp-items="Model.Items"></select> The rendered select contains Dynamic and Static optgroup elements. Items without a group remain outside the groups. section 18.2.4
Listing 18.7 Adding Groups to SelectListItems to create optgroup elements
public class SelectListsModel: PageModel
{
[BindProperty]
public IEnumerable<string> SelectedValues { get; set; } #1
public IEnumerable<SelectListItem> Items { get; set; }
public SelectListsModel() #2
{
var dynamic = new SelectListGroup { Name = "Dynamic" }; #3
var @static = new SelectListGroup { Name = "Static" }; #3
Items = new List<SelectListItem>
{
new SelectListItem {
Value= "js",
Text="Javascript",
Group = dynamic #4
},
new SelectListItem {
Value= "cpp",
Text="C++",
Group = @static #4
},
new SelectListItem {
Value= "python",
Text="Python",
Group = dynamic #4
},
new SelectListItem { #5
Value= "csharp", #5
Text="C#", #5
}
};
}
}
#1 Holds the selected values where multiple selections are allowed
#2 Initializes the list items in the constructor
#3 Creates a single instance of each group to pass to SelectListItems
#4 Sets the appropriate group for each SelectListItem
#5 If a SelectListItem doesn’t have a Group, it won’t be added to an <optgroup>.
View the complete grouped SelectListItem example, including dynamic and static groups. section 18.2.4
