a blog for those who code

Thursday 1 September 2016

What is TempData and how it is different than ViewBag

In this post we will be discussing about TempData and how it is different than ViewBag in Asp.Net MVC. In MVC you can pass data from controller to view using ViewBag and ViewData but neither of them can be used to pass data from view to controller. TempData on the other hand is intend to hold any data that you want to transfer from one controller action to another controller action in the same request.

When you need to retain data temporarily between re-directions, the TempData object can be used. It is a dictionary object that is derived from TempDataDictionary class and stored in short live session. TempData requires typecasting for getting data and check for null values to avoid error.


TempData is mainly used for one-time messages such as form validation errors or info messages.

Example of TempData :


public ActionResult Cont1()
{
  TempData["value1"] = "Value 1";
  TempData["value2"] = "Value 2";
  
  return View();
}

public ActionResult Cont2()
{
  if(TempData["value1"] != null)
    var value1 = TempData["value1"].ToString(); // Getting value from TempData
  if(TempData["value2"] != null)
    var value2 = TempData["value2"].ToString(); // Getting value from TempData
  
  return View();
}

So both value1 and value2 will be persisted in Cont2 controller but will not be available in any further requests. To retain values of TempData you need to take advantage of Keep() function as shown below.

public ActionResult Cont2()
{
  if(TempData["value1"] != null)
    var value1 = TempData["value1"].ToString(); // Getting value from TempData
  
  TempData.Keep();
  return View();
}


How it is different than ViewBag


It is different than ViewBag because TempData stays for a subsequent HTTP Request as opposed to ViewBag or ViewData which stays only for current request. So, TempData can be used to pass data between controller actions as well as redirects whereas ViewBag can pass data from controller to view for its current request.

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

1 comment: