ASP.NET MVC - TempData - A Closer Look



As an ASP.Net MVC developer, you may frequently be involved with terms like Tempdata, viewdata and viewbag. In this post, I’m going to take a close look atTempData and how it works. You can also read this same article in my blog. If you want to read the difference between Viewbag, ViewData and Tempdata then read it from my blog post.

For explanation purposes, I’m going to create a small MVC project with 3 views and a controller.
  1. Index.cshtml This is the default view, which is loaded by the default action method.
  2. Page1.cshtml This is the another view, called by redirect.
  3. Page2.cshtml Yet another view, called by redirect

And the controller named as.

  1. DefaultController.cs 

TempData

We will start with TempData.As a first step, I will set the value of TempData in the Action method “Index”, like below.

  1. using System.Web.Mvc;  
  2. namespace SessionHandlingInMVC.Controllers   
  3. {   
  4.     public class  DefaultController : Controller   
  5.     {   
  6.         // GET: Default           
  7.        public ActionResult Index()   
  8.         {               
  9.           TempData["MyTempDataValue"] = "Value initialized in Index Action Method";   
  10.           return View();   
  11.         }   
  12.           
  13.        public ActionResult Page1()   
  14.         {   
  15.             return View("Page1");   
  16.         }  
  17.        public ActionResult Page2()   
  18.         {   
  19.            return View("Page2");   
  20.         }   
  21.     }   
  22. }  
 In the “Index” view, we can get the value of the initialized “Tempdata” value as below. 
  1. <h2>Index Page</h2>  
  2. <p>   
  3.    @{   
  4.        string strTempDataValue = (string)TempData["MyTempDataValue"];   
  5.     }   
  6.     @strTempDataValue   
  7. </p>  
Please take a close look how the value is retrieved from the “TempData”.You can’t directly assign to it the specific type.  A typecasting is needed, when you retrieve the value from Tempdata. The above snippet just gets the value from TempData dictionary and prints it on.

In the next snippet, I’m going to change the above snippet a little bit like below. 
  1. <h2>Index Page</h2>   
  2. <p>   
  3.    @{   
  4.        string strTempDataValue = (string)TempData["MyTempDataValue"];   
  5.     }   
  6.        @strTempDataValue  
  7.     @{   
  8.        string strAnotherRead =  (string)TempData["MyTempDataValue"];   
  9.     }   
  10.     @strAnotherRead   
  11. </p>  
In the above snippet, we have read the TempData value twice. As a result the value also printed twice in the view.

The above result confirms that, you can read the TempData value inside the current request in as much time as possible. 

In the following snippet, I’m going to read the value of the TempData in the next view, which is rendered by the action method “Page1”. 
  1. <h2>Page1</h2>   
  2. <p>   
  3.     @{   
  4.         string strTempDataValueInPage1 = (string)TempData["MyTempDataValue"];   
  5.     }   
  6.       
  7. @strTempDataValueInPage1   
  8. </p>  
 In order to test the above scenario, first you must render the view “Index” (since in that action method alone the tempdata value is initialized) and then you call the “Page1” view. As you can see, TempData value is not available in the next request.
 
  
Wait! The conclusion is not yet over. I want to try something more. That is, as per the above codes.
  1. First I render the “Index” page, where the Tempdata value is read and print it.
  2. After I call the action method “Page1”.
What will happen if I didn’t read the value of Tempdata in “Index.cshtml” view and try to read the “Page1.cshtml” view? In order to test, I made the below changes in Index view.

Index.cshtml
  1. <h2>Index Page</h2>   
  2. <p>   
  3.     No Temp Data read here   
  4. in Index.cshtml   
  5. </p>  
 Page1.cshtml 
  1. <h2>Page1</h2>   
  2. <p>   
  3.     @{   
  4.         string   
  5. strTempDataValueInPage1 = (string)TempData["MyTempDataValue"];   
  6.     }   
  7.       
  8. @strTempDataValueInPage1   
  9. </p>  
Now, you get the value in the value of Tempdata in the next request. That means, your first request renders the “Index” page, and the next request renders “Page1”.
 
 
  
If you refresh the above page, you will get the result as below: that is, the Tempdata is unavailable once it read. So you get the Tempdata value as empty.

So the conclusion is - After Tempdata value is initialized and it’s not yet read in the current request, then it will be available in the next request. Once it is read, it will not available. 

A few words about Keep() and Peek() method

After you read the tempdata, if you call the keep method, it will marks the all tempdata keys or specific key for retention. If you want to fetch the key and mark the key for retention (keep the key for the next request) then you can go with Peek method.

Connection between Session and Tempdata

Yes, Tempdata uses “Session” object in the backend. That is, whenever you use a tempdata it will be handled by session. But the main difference is, the Tempdata will be removed (by default) after the first read.

At the same time, you may have a doubt, that is  tempdata specific to the user as like as “Session”? The answer is Yes. Since the Tempdata, is backed up with Session, Tempdata is also specific to user, like Session object.

Also, the other question is, since the Tempdata is backed up with Session, what will happen if we go with the same key for session and Tempdata as like below:

The answer is it won’t colloid. It will considered as a different one and it will serve its own purpose as per the convention.

In summary
  1. TempData stores the value using key.
  2. TempData is backed up with Session.
  3. Need type casting when the stored value is retrieved.
  4. The life time of tempdata is little bit tricky. It will be available until you read it first time. After you read it, it will be marked for deletion. So in the next request, it won’t be available.  However, you can extend its life time by using keep and peek method.
Readers, did I miss anything? Share your feedback as comments.

Up Next
    Ebook Download
    View all
    Learn
    View all