Categories : ASP.NET Core
Author : Date : Feb 7, 2022
Tags : asp.net core, DropDownList, Group, Tag Helper
This blog explains how to group options in a DropDownList in ASP.NET Core. Let’s look at it with an example.
This example is going to bind the list of movie names grouped by the release year with the Selected Tag Helper.
The following is the MyViewModelSample class. It has two properties, SelectedMovieID and MoviesList. The SelectedMovieID property will have the selected value of the drop-down list. The MoviesListproperty is what sets up a list of movies.
MyViewModelSample.cs
The following is a controller code. This controller has 2 action methods, Sample() and SampleSubmit(). In the Sample() action method, values are assigned and passed to the view. In SampleSubmit() action method, the selected movie ID is retrieved from the view and passed to another view to be displayed on the page.
HomeController.cs
The following is a sample view. @Model.MoviesList is assigned to asp-items to bind a list of movie names. The SelectedMovieID property is assigned to the asp-for, thus providing the selected result.
Sample.cshtml
Below is a result view. The selected move ID will be displayed here.
SampleResult.cshtml
The following image is the output of the code above. Here you can see the names of the movies grouped by the movie release year. When the page is submitted it returns the selected movie ID.
If you have any questions, please leave a comment below.