Bind ASP Model To SelectList In _Layout Page Using Sessions In ASP.NET Core

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.
  1. public class Store    
  2. {    
  3.    [Key]    
  4.    public int Id { getset; }    
  5.    [Display(Name ="Store Name")]    
  6.    [Required(ErrorMessage ="Name is required")]    
  7.    public string Name { getset; }    
  8.    public string Description { getset; }      
  9. }     
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.
  1. Using session
  2. 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 >.
 
Bind ASP Model to SelectList in _Layout page using Sessions in ASP.NET Core
 
This is our model of stores.
 
Bind ASP Model to SelectList in _Layout page using Sessions in ASP.NET Core
 
Now add a controller with views to add some stores.
 
Bind ASP Model to SelectList in _Layout page using Sessions in ASP.NET Core
 
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.
 
Bind ASP Model to SelectList in _Layout page using Sessions in ASP.NET Core
 
So here is the index page. After adding few stores.
 
Bind ASP Model to SelectList in _Layout page using Sessions in ASP.NET Core
 
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.
  1. public IActionResult Index() {  
  2.     List < Store > stores = new List < Store > ();  
  3.     stores = GetAllStores();  
  4.     string storesJson = JsonConvert.SerializeObject(stores);  
  5.     HttpContext.Session.SetString(SessionKey_Stores, storesJson);  
  6.     return View();  
  7. }   
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.
 
Bind ASP Model to SelectList in _Layout page using Sessions in ASP.NET Core
 
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.
  1. private List < Store > GetAllStores() {  
  2.     List < Store > store = new List < Store > ();  
  3.     try {  
  4.         if (_context != null) {  
  5.             store = _context.Store.ToList();  
  6.         }  
  7.     } catch (Exception ex) {}  
  8.     return store;  
  9. }   
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.
 
Bind ASP Model to SelectList in _Layout page using Sessions in ASP.NET Core
 
Add following session related services in ConfigureServices() function in Startup.cs class
Bind ASP Model to SelectList in _Layout page using Sessions in ASP.NET Core
 
Here is the code.
  1. services.AddDistributedMemoryCache(); //for session    
  2. services.AddSession(options => {  
  3.     options.Cookie.Name = "ATT.Session";  
  4.     options.IdleTimeout = TimeSpan.FromMinutes(10); // 10 minutes session    
  5.     options.Cookie.HttpOnly = true;  
  6.     options.Cookie.IsEssential = true;  
  7. });   
Now in the Configure function add this to enable sessions use.
 
Bind ASP Model to SelectList in _Layout page using Sessions in ASP.NET Core
 
Here is the code ..
  1. app.UseSession(); // for sessions   
Now it's time to fetch this data on the Razor page which is _Layout.cshtml in our case.
 
Bind ASP Model to SelectList in _Layout page using Sessions in ASP.NET Core
 
Stores data has been fetched using a session-based key.
 
Now you can bind this data to SelectList as described below.
  1. <select id="select_storeId" class="nav-item" asp-items="@(new SelectList(storesList,"Id","Name"))">    
  2.    <option>Stores</option>    
  3. </select>      
Now if you run the project you can see the bound list.
 
Bind ASP Model to SelectList in _Layout page using Sessions in ASP.NET Core