ASP.NET MVC - TempData - A Closer Look

TempData

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 another view, called a redirect.
  3. Page2.cshtml Yet another view, called by redirect

The controller is named as.

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.

using System.Web.Mvc;

namespace SessionHandlingInMVC.Controllers
{
    public class DefaultController : Controller
    {
        // GET: Default
        public ActionResult Index()
        {
            TempData["MyTempDataValue"] = "Value initialized in Index Action Method";
            return View();
        }
        
        public ActionResult Page1()
        {
            return View("Page1");
        }
        
        public ActionResult Page2()
        {
            return View("Page2");
        }
    }
}

In the “Index” view, we can get the value of the initialized “Tempdata” value as below.

<h2>Index Page</h2>
<p>
    @{
        string strTempDataValue = (string)TempData["MyTempDataValue"];
    }
    @strTempDataValue
</p>

Please take a close look at 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.

<h2>Index Page</h2>
<p>
    @{
        string strTempDataValue = (string)TempData["MyTempDataValue"];
    }
    @strTempDataValue

    @{
        string strAnotherRead = (string)TempData["MyTempDataValue"];
    }
    @strAnotherRead
</p>

In the above snippet, we have read the TempData value twice. As a result the value is also printed twice in the view.

 TempData value

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”.

<h2>Page1</h2>
<p>
    @{
        string strTempDataValueInPage1 = (string)TempData["MyTempDataValue"];
    }
    @strTempDataValueInPage1
</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.

Page 1

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 don’t read the value of Tempdata in the “Index.cshtml” view and try to read the “Page1.cshtml” view? In order to test, I made the below changes in the Index view.

Index.cshtml

<h2>Index Page</h2>
<p>
    No Temp Data read here in Index.cshtml
</p>

Page 1. .cshtml

<h2>Page1</h2>
<p>
    @{
        string strTempDataValueInPage1 = (string)TempData["MyTempDataValue"];
    }
    @strTempDataValueInPage1
</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”.

Index

Application name

If you refresh the above page, you will get the result below: that is, the Tempdata is unavailable once it is read. So you get the Tempdata value as empty.

Tempdata value empty

So the conclusion is that 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 be available.

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

After you read the tempdata, if you call the keep method, it will mark all tempdata keys or specific keys 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 the Peek method.

Connection between Session and Tempdata

Yes, Tempdata uses a “Session” object in the backend. That is, whenever you use a tempdate 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, 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 the user, like the 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 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.

Summary

  1. TempData stores the value using the key.
  2. TempData is backed up with Session.
  3. Need type casting when the stored value is retrieved.
  4. The lifetime of tempdata is a little bit tricky. It will be available until you read it the 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 lifetime by using the keep and peek method.

Readers, did I miss anything? Share your feedback as comments.


Similar Articles