Wednesday, August 15, 2018

State Management techniques In ASP.NET MVC


State Management In ASP.NET MVC.
 We all know that HTTP is a state less protocol. Hence, If we want to pass data from one page to another page or even on multiple  
 visits of the same page, then we need to use the State management techniques to store user specific data.  
 Here, i am going discuss various techniques to pass the data from a Controller to View or Controller to Controller.  
 ASP.NET MVC doesn’t support ViewState or Server controllers.  
 To achieve state management in ASP.NET MVC, there are four basic ways which are given as following.  
 1.ViewData  
 2.ViewBag  
 3.TempData  
 4.Sessions  
 1.ViewData  
 ViewData is used to pass the data from Controller to View.It is derived from ViewDataDictionary class, it requires typecasting for complex datatypes   
 and it requires a null check to void exceptions.  
 Controller  
 public ActionResult Index()   
     {   
       ViewData["CurrTime"] = DateTime.Now;   
       return View();   
     }   
 HTML Index.cshtml Code  
 @ViewData["CurrentTime"];  
 2.ViewBag  
 ViewBag is also used to pass data from Controller to View. It is a dynamic property which uses the Dynamic feature of C# 4.0. And, the  
 Dynamic keyword internally uses reflection.  
 Controller Code  
 public ActionResult Index()   
     {   
       ViewBag.CurrTime = DateTime.Now;   
       return View();   
     }   
 html Index.cshtml code  
 @ViewBag.CurrentTime  
 3.TempData  
 TempData is used to pass the data from Action to Action or Controller to Controller, and then to View. It keeps the information for single HTTP Request.  
 It is derived from TemDataDictionary and along with this, it requires typecasting for complex data types and it requires a null check to void exceptions.  
 Controller Code  
 public ActionResult Index()   
     {   
       TempData["CurrTime"] = DateTime.Now;   
       return View();   
     }   
 Html Index.cshtml code  
 @TempData["CurrTime"];  
 4.Session  
 If you want to store the data and maintain it for multiple requests, then use session variables.  
 Controller Code  
 public ActionResult Index()   
     {   
 Session["CurrTime"] = DateTime.Now;   
       return View();   
     }   
 Html Index.cshtml Code  
 @Session["CurrentTime"];  

0 comments:

Post a Comment