Manage session in MVC


Introduction

In my previous article, we have discussed various elements of MVC. This blog describes how to manage session in MVC with code example.

Getting Started

ASP.NET MVC provides three ways (TempData, ViewData and ViewBag) to manage session, apart from that we can use session variable, hidden fields and HTML controls for the same. But like session variable these elements could not preserve values for all request, value persistence varies depending the flow of request. For example ViewData maintains data when you move from controller to view only.





TempData

TempData in ASP.NET MVC is basically a dictionary object derived from TempDataDictionary.
TempData internally uses session variable and stays for a subsequent HTTP Request. Means it maintains data when you move one controller to another controller or one action to another action. As this is a dictionary object null checking and typecasting requires while using it.

Below example shows how to retrieve and put data from or into tempdata both in controller and view .
 //storing data into tempdata  
       TempData["Name"] = "Kailash";  
       TempData["height"]=8.5;  
 //retrieving data from tempdata in controller  
       string name = TempData["Name"].ToString();  
       double height = Convert.ToDouble(TempData["height"]);  
 //retrieving data from tempdata in view using asp.net enging  
       <label><%TempData["Name"].ToString();%></label>  
       <label><%Convert.ToDouble(TempData["height"]); %></label>  
      @if (!TempData["Name "] =null)   
      {  
       @TempData["Name "];   
      }  
      @if (!TempData["height "] =null)   
      {  
       Convert.ToDouble(@TempData["height"]);  
      }  
TempData gets destroyed immediately after it’s used (once value is read from tempdata) in subsequent HTTP request, so no explicit action required, if you want preserve value in the subsequent request after using need to call keep method or peek method. See the below example.

ViewData

ViewData maintains data when you move from controller to view. It is also a dictionary object and derived from ViewDataDictionary. As Data is stored as Object in ViewData, while retrieving, the data it needs to be Type Casted to its original type as the data is stored as objects and it also requires NULL checks while retrieving.

Below example shows how to retrieve and put data from or into ViewData both in controller and view .
 //storing data into viewdata  
       ViewData["ViewDataName"] = "abc";  
       ViewData["ViewDataHeight"] = 2.56;  
       //retrieving data from viewdata in controller  
        string abc = ViewData["ViewDataName"].ToString();  
       double ViewDataHeight = Convert.ToDouble(TempData["ViewDataHeight"]);  
       //retrieving data from viewdata in view using asp.net enging  
   <label><%ViewData["ViewDataName"].ToString();%></label>  
     <label><%Convert.ToDouble(ViewData["ViewDataHeight"]); %></label>  
 @if (!ViewData["ViewDataName "] =null)   
 {  
 @ViewData["ViewDataName "];   
 }  
 @if (!ViewData["ViewDataHeight "] =null)   
 {  
 Convert.ToDouble(ViewData["ViewDataHeight"]);  
 }  

ViewBag

The ViewBag is a dynamic type property of ControllerBase class which is the base class of all the controllers. It’s a dynamic wrapper around ViewData casting is not required when you use ViewBag. ViewBag only transfers data from controller to view, not visa-versa. ViewBag values will be null if redirection occurs.

ViewBag support any number of properties or values. if same value found then it will only consider last value assigned to the property.

Below various example of ViewBag.
 //storing data into viewdata  
       ViewBag.Name = "Kailash";  
       ViewBag.Height = 2.24;  
       //retrieving data from viewdata in controller  
        string ViewBagname= ViewBag.Name;  
       double ViewDataHeight = ViewBag.Height;  
       //retrieving data from viewdata in view using asp.net enging  
   @ViewBag.Name;   
  @ViewBag.Height ;  
  @Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))   
 @Html.DropDownListFor(x => x.accountId, new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))  
As like ASP.NET session and Hidden fields can be used. session variables we can maintain data from any entity to any entity and hidden fields help to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Summary

Hope this article will help you to get brief idea about session management in MVC. Enjoy and happy coding.

Thanks