Using OptionGroups with the select Tag Helper
- Represents the optgroup HTML element and its attributes. In a select list, multiple groups with the same name are supported. They are compared with reference equality.
SelectListGroup Class
- Namespace:Microsoft.AspNetCore.Mvc.Rendering
- Assembly:Microsoft.AspNetCore.Mvc.ViewFeatures.dll
- Package:Microsoft.AspNetCore.App.Ref v5.0.0
Step 1: Create a Model class in Models Folder
public class GroupItemsViewModel { public GroupItemsViewModel() { this.Mobiles = new List<SelectListItem>(); } public List<SelectListItem> Mobiles { get; set; } public string Mobilename { get; set; } }
Step 2: Controller Action Code
public IActionResult SelectGroup() { GroupItemsViewModel viewModel = new GroupItemsViewModel(); SelectListGroup mobilestype = new SelectListGroup() { Name = "Smartphones" }; viewModel.Mobiles.Add(new SelectListItem() { Text = "Samsung", Group = mobilestype }); viewModel.Mobiles.Add(new SelectListItem() { Text = "MI", Group = mobilestype }); SelectListGroup mobilestype1 = new SelectListGroup() { Name = "Multimedia" }; viewModel.Mobiles.Add(new SelectListItem() { Text = "Micromax", Group = mobilestype1 }); viewModel.Mobiles.Add(new SelectListItem() { Text = "Nokia", Group = mobilestype1 }); return View(viewModel); }
Step 3: View
<select asp-for="Mobilename" asp-items="@Model.Mobiles" class="form-control"> <option selected disabled value="">--Select Mobile--</option> </select>
Result :