How To Use TempData In ASP.NET

Tempdata is another beautiful feature in ASP.Net MVC. We use TempData just like we use ViewData. We’ve already discussed a lot about ViewBag and ViewData stuff. TempData is a container in which we maintain the state in consecutive requests. TempData is used to store the temporary data. It is using the session under the hood. But it is not exactly a session. It automatically clears in the application but we need to explicitly clear our session variables. TempData is actually the TempDataDictionary type.

The value we can add in ViewData is of object type and the key would be string type. Similarly, we deal with TempData as we do ViewData. Let’s start with a simple example.

  1. public class StudentController : Controller  
  2. {  
  3.     // 1st Request  
  4.     public ActionResult Index()  
  5.     {  
  6.         TempData["name"] = "Usama";  
  7.         TempData["institute"] = "GCUF";  
  8.    
  9.         return View();  
  10.     }  
  11.    
  12.     // 2nd Request  
  13.     public ActionResult Details()  
  14.     {  
  15.         return View();  
  16.     }  
  17.  }  

Now create these action views and use the TempData there.

  1. @{  
  2.     var name = "";  
  3.     var institute = "";  
  4.     if (TempData.ContainsKey("name"))  
  5.     {  
  6.         name = TempData["name"] as string;  
  7.     }  
  8.     if (TempData.ContainsKey("institute"))  
  9.     {  
  10.         institute = TempData["institute"] as string;  
  11.     }  
  12. }  
  13.    
  14. <h2> @name </h2>  
  15. <h2> @institute </h2>  

This is how we use the TempData. It is important to cast the ViewData and TempData variables before use. And we also check the values of these variables to handle the null reference exception as we’re doing here in this example. It automatically clears on the third request because its life is only limited to the subsequent request. Now let’s just add a Url.Action on Index View.

  1. @Html.ActionLink("Details""Details""Student")  

Now run the application. You’ll see that TempData is only working in Index view and it is not showing any content in Details view. Actually we’re initializing the TempData variable in Index action and then the consecutive request is Index view where we’re using TempData variables. But then when we redirect to the Details action view, it is not showing anything, because here TempData clears.

Difference of ViewBag, ViewData And TempData

The major difference is we use ViewBag and ViewData to pass the data from controller action to views. But we can’t access these variables in controller actions. But we can use the TempData in our actions as well. Let’s take a look,

Comment the Index view code.

  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.    
  5. @Html.ActionLink("Details""Details""Student")  
  6.    
  7. @*@{  
  8.     var name = "";  
  9.     var institute = "";  
  10.     if (TempData.ContainsKey("name"))  
  11.     {  
  12.         name = TempData["name"] as string;  
  13.     }  
  14.     if (TempData.ContainsKey("institute"))  
  15.     {  
  16.         institute = TempData["institute"] as string;  
  17.     }  
  18. }  
  19.    
  20. <h2> @name </h2>  
  21. <h2> @institute </h2>*@  

And now use TempData variables in Details action and use them into the view with ViewBag.

  1. // 2nd Request  
  2. public ActionResult Details()  
  3. {  
  4.     if (TempData.ContainsKey("name"))  
  5.     {  
  6.         ViewBag.Name = TempData["name"] as string;  
  7.     }  
  8.    
  9.     if (TempData.ContainsKey("institute"))  
  10.     {  
  11.         ViewBag.Institute = TempData["institute"] as string;  
  12.     }  
  13.    
  14.     return View();  
  15. }  
And here is the Details View. 
  1. @{  
  2.     ViewBag.Title = "Details";  
  3. }  
  4.    
  5. <h2> @ViewBag.Name </h2>  
  6. <h2> @ViewBag.Institute </h2>  
Now look we’re using TempData variables in Details actions, it’s a consecutive second request. Here we have the values in TempData variables. Now run the application and move from Student/ request to Details page and you’ll see the results.

TempData

This is how we use and get the values from TempData in controller actions as well and it was not possible in ViewBag and ViewData scenarios.

How to Maintain the State of TempData

Now what we want is to maintain the state of TempData on the second request to make the values available on the third request as well. For  this purpose, we just need to use the keep function with TempData variables. First of all make the third action in Students controller and copy the code from Details action and paste it into About action.
  1. public ActionResult About()  
  2. {  
  3.     if (TempData.ContainsKey("name"))  
  4.     {  
  5.         ViewBag.Name = TempData["name"] as string;  
  6.     }  
  7.    
  8.     if (TempData.ContainsKey("institute"))  
  9.     {  
  10.         ViewBag.Institute = TempData["institute"] as string;  
  11.     }  
  12.    
  13.     return View();  
  14. }  
Don’t bother about the same names of ViewBag variables because they work only with action to view, not for action to action. So these are the new variables. Now  on to the details action and just add a single line to maintain its state for the next request.
  1. public ActionResult Details()  
  2. {  
  3.     if (TempData.ContainsKey("name"))  
  4.     {  
  5.         ViewBag.Name = TempData["name"] as string;  
  6.     }  
  7.    
  8.     if (TempData.ContainsKey("institute"))  
  9.     {  
  10.         ViewBag.Institute = TempData["institute"] as string;  
  11.     }  
  12.    
  13.     TempData.Keep();  
  14.    
  15.     return View();  
  16. }  
Now use the ViewBag variables in About page as well how we do in Details page. And also add a html.actionlink on details page to navigate to the about page. And now run the application.

TempData

And now it is working on the third request as well.

TempData with Complex Types

The plain types are like int, float, and string. These are the built-in datatypes but the datatype which is defined by the developer where we’re using multiple types  is inside and it is based on the requirements. This is called complex types like class, and struct. It is not important to mention but to make the concept clear to the reader, I would say we also define the different operations or function that we can manipulate on this type. To come back to the point, don’t worry about the complex types. If you know how to use classes with ViewBag or ViewData then it is 100% exactly the same with TempData.Take a look at one simple example.
  1. namespace SMPL.Controllers  
  2. {  
  3.     public class StudentController : Controller  
  4.     {  
  5.         // 1st Request  
  6.         public ActionResult Index()  
  7.         {  
  8.             Student std = new Student  
  9.             {  
  10.                 Name = "Muhammad",  
  11.                 Institute = "GCUF"  
  12.             };  
  13.    
  14.             TempData["info"] = std;  
  15.    
  16.             return View();  
  17.         }  
  18.     }  
  19.    
  20.     public class Student  
  21.     {  
  22.         public string Name { get; set; }  
  23.         public string Institute { get; set; }  
  24.     }  
  25. }  
And here is the view of our Index action. 
  1. @using SMPL.Controllers  
  2.    
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.    
  7. <h2> @((TempData["info"] as Student).Institute)</h2>  
  8. <h2> @((TempData["info"] as Student).Name)</h2>  
And yes it is working fine.

Conclusion

So the conclusion is we use TempData to store the data and we access it in consecutive requests. Internally it is using session. Its type is TempDataDictionary. It automatically clears after subsequent requests and we need to manually clear the session variable. We can use TempData in controller actions as well. We need to cast the TempData and ViewData as well before we consume them in our action or view. And the final suggestion is, only use ViewBag, ViewData, TempData when you really need them. If you can complete your task with other better techniques then go ahead with those techniques, like ViewModel is the alternative option of ViewBag and ViewData. So take a deep dive and explore things. Happy Coding.


Similar Articles