Manage session in MVC

Introduction

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

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. This 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 require 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 the value is read from temp data) in a subsequent HTTP request, so no explicit action required if you want to preserve value in the subsequent request after using the 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 needs to be Type Cast 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 supports any number of properties or values. if the same value found then it will only consider the 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

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

نموذج الاتصال