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.
- public IActionResult Index() {
- List < Store > stores = new List < Store > ();
- stores = GetAllStores();
- string storesJson = JsonConvert.SerializeObject(stores);
- HttpContext.Session.SetString(SessionKey_Stores, storesJson);
- return View();
- }
Here we are using a function GetAllStores() which is just doing the database call to fetch stores. In the last line we are adding our model data that has been converted into json is assigning against a key.
We've declared the key in a class above function.
Session always stores data in key and value pairs. So we've assigned all the Json data against a key in order to fetch it in razor page or some other place where is session is accessible.
- private List < Store > GetAllStores() {
- List < Store > store = new List < Store > ();
- try {
- if (_context != null) {
- store = _context.Store.ToList();
- }
- } catch (Exception ex) {}
- return store;
- }
One more thing that I forgot to tell you is to add few configurations in ASP.NET Core project in order to use sessions, Open the solution explorer and go to the Startup.cs class.
Add following session related services in ConfigureServices() function in Startup.cs class
Here is the code.
- services.AddDistributedMemoryCache();
- services.AddSession(options => {
- options.Cookie.Name = "ATT.Session";
- options.IdleTimeout = TimeSpan.FromMinutes(10);
- options.Cookie.HttpOnly = true;
- options.Cookie.IsEssential = true;
- });
Now in the Configure function add this to enable sessions use.
Here is the code ..
Now it's time to fetch this data on the Razor page which is _Layout.cshtml in our case.
Stores data has been fetched using a session-based key.
Now you can bind this data to SelectList as described below.
- <select id="select_storeId" class="nav-item" asp-items="@(new SelectList(storesList,"Id","Name"))">
- <option>Stores</option>
- </select>
Now if you run the project you can see the bound list.