All about tempdata in Asp.Net MVC

TempData in ASP.NET MVC is basically a dictionary object derived from TempDataDictionary. TempData stays for a subsequent HTTP Request as opposed to other options (ViewBag and ViewData) those stay only for current request. So, TempData can be used to maintain data between controller actions as well as redirects.

Note: Just like ViewData, typecasting and null checks required for TempData also in order to avoid errors.

Let’s see how we can use TempData in a practical scenario to pass data from one controller action to another.


 //Controller Action 1 (TemporaryEmployee)
 public ActionResult TemporaryEmployee()
{
                Employee employee = new Employee
                {
                        EmpID = "121",
                        EmpFirstName = "Imran",
                        EmpLastName = "Ghani"
                };
                TempData["Employee"] = employee;
                return RedirectToAction("PermanentEmployee");
}

 //Controller Action 2(PermanentEmployee)
 public ActionResult PermanentEmployee()
{
               Employee employee = TempData["Employee"] as Employee;
               return View(employee);
 }




  • “TempData” will be persisted depending on 4 CONDITIONS:
  1. Not Read
  2. Normal Read
  3. Read and Keep
  4. Peek and Read



Condition 1 (Not read): If you set a “TempData” inside your action and if you do not read it in your view, then “TempData” will be persisted for the next request.

Condition 2 (Normal Read): If you read the “TempData” normally like the below code, it will not persist for the next request.


stringstr = TempData["MyData"];

Even if you are displaying, it’s a normal read like the code below:


@TempData["MyData"];


Condition 3 (Read and Keep): If you read the “TempData” and call the “Keep” method, it will be persisted.


@TempData["MyData"];
TempData.Keep("MyData");


Condition 4 ( Peek and Read): If you read “TempData” by using the “Peek” method, it will persist for the next request.


stringstr = TempData.Peek("Td").ToString();


Comments