In this article, we are going to learn how to bind a model to a DropdownList or SelectList in ASP.NET Core using sessions.
Note
SelectList is the alternate name of a Combobox in classical .NET applications.
Let's suppose we have a model that represents stores in a factory.
This is the store model class.
- public class Store
- {
- [Key]
- public int Id { get; set; }
- [Display(Name ="Store Name")]
- [Required(ErrorMessage ="Name is required")]
- public string Name { get; set; }
- public string Description { get; set; }
- }
We need something like this in _Layout.cshtml page where we don’t have model Model available in Razor page like all the other pages. So the problem with regular binding is that _Layout.cshtml page always gets's reload whenever we open a new page in ASP.NET web application. Mean if you go with the regular binding, you'll get an exception which will be about the availability of data source property of SelectList control or source of data of the control which is bound to some data source.
We can handle this using different ways which are given below.
- Using session
- Using ASP.NET Core services
Asp.net core services include the following major services.
- Singleton Services
- Scoped Services
- Transient Services
Handling this kind of situation totally depends upon your use case. For a limited user application, you can go with sessions but for the web applications which have a large number of users, it is not recommended to use the session to bind such kind of data to controls. For large web applications, the service-based solution is a recommended approach.
After adding this model to your ASP.NET Core project make a controller of it and add few items < stores >.

This is our model of stores.

Now add a controller with views to add some stores.

Once the controller with views is added as given below, you can add few stores to your database. But before adding stores to the database don’t forget to add migrations in your project otherwise you wouldn't be able to add your desired data.

So here is the index page. After adding few stores.

We want to bind these names of stores in a dropdown list located in _Layout.cshtml page.
_Layout.cshtml is the base layout page which renders all the time when any of the web page loads. In our case, the very first page which is loading is the Index Page of HomeController. So all the code to fetch stores will be done there.







Join the conversation! Your thoughts help the community grow.