Tuesday 11 August 2015

TempData

TempData is also a dictionarylike ViewData.
The difference is the life cycle of the object. TempData keeps the information for the time of an HTTP Request. 
It helps to maintain data when you move from one controller to other controller or from one action to other action. Use it only when you are sure that next request will be redirecting to next view beacse it is short lived.
It internally uses session variables. 
It requires typecasting for complex data type and check for null values to avoid error just like ViewData.
I generally use it  to store only one time messages like error messages, validation messages.
public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}
public ActionResult About() 
{     
    var model= TempData["ModelName"];     
    return View(model); 
}


Once “TempData” is read in the current request it’s not available in the subsequent request. If we want “TempData” to be read and also available in the subsequent request then after reading we need to call “Keep” or Peek  method as shown in the code below.

 var model= TempData.Keep("ModelName");
 var model= TempData.Peek("ModelName");

I always prefer using the peek than keep.

No comments:

Post a Comment