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

Popular posts from this blog

Restore the lost focus of Auto post back controls in asp.net update Panel control

Clone a generic list in C# using extension method

Disable backspace key using Jquery

Add Comma automatically while entering amounts in textbox using Javascript

Step by step migration of ASP.NET Core 2.2 to 3.1

Source Code Beautifier And Format Source Code For Blogger and Websites

Remove Owin from MVC 5 Application and use asp.net custom forms authentication

How to Import CSV File and bind csv file data to gridview in asp.net using c#

Email validation using regular expression in jQuery