Back to: ASP.NET Core Tutorials For Beginners and Professionals
TempData in ASP.NET Core MVC
In this article, I am going to discuss ASP.NET Core MVC TempData with Examples. Please read our previous article, where we discussed ViewModels in the ASP.NET Core MVC application. As part of this article, we are going to discuss the following pointers, which are related to MVC TempData.
- Why do we need TempData in the ASP.NET Core MVC Application?
- What exactly is TempData in ASP.NET Core MVC?
- How to use TempData?
- How to Pass and Retrieve Data from TempData?
- How to Retain TempData values in the Consecutive Request in ASP.NET Core MVC?
Why do we need TempData in the ASP.NET Core MVC Application?
As we already discussed in our previous articles, we can use ViewData, ViewBag, and Strongly Typed Models to pass the data from a controller action method to a view. Now, we will see another approach to send the data from the controller action method to a view in ASP.NET Core MVC Application using the TempData.
The limitation of both ViewData and ViewBag is they are limited to one HTTP request only. So, if redirection occurs, their values become null, meaning they will lose the data they hold. In many real-time applications, we may need to pass the data from one HTTP Request to the next subsequent HTTP Request. For example, we may need to pass the data from one controller to another or one action method to another within the same controller. Then in such situations like this, we need to use TempData in ASP.NET Core MVC Application.
What is TempData in ASP.NET Core MVC?
In ASP.NET Core MVC, TempData is a feature that allows us to store temporary data that will be available for the next request. It’s a mechanism to pass data between different actions or controllers during the lifetime of a user’s session. TempData is typically used when you need to show a message or provide some information to the user after a redirect.
TempData is implemented using the session state. It stores data in the session between requests, but unlike regular session data, TempData is meant to be short-lived and is removed automatically once it’s read or after the subsequent request is processed.
The TempData in ASP.NET Core MVC Application is one of the mechanisms to pass a small amount of temporary data from a controller action method to a view and from a controller action method to another action method within the same controller or to a different controller. TempData value will become null once the subsequent request is completed by default. But if you want, then you can also change this default behavior. If you look at the definition Controller class, you will find the following signature of the TempData property.
As you can see in the above image, the data type of the TempData is ITempDataDictionary. Let us see the definition of the ITempDataDictionary class.
As you can see, the ITempDataDictionary class implements the IDictionary interface. So, we can say that the TempData in ASP.NET Core MVC is a dictionary object. As it is a dictionary object, it will store the data in the form of key-value pairs where each key must be a string, and the value that we are passing to the dictionary will be stored in the form of an object type.
How to Pass and Retrieve Data From TempData in ASP.NET Core MVC?
The most important point you need to remember is that it stores the data in the form of an object, so while retrieving the data from TempData, type casting is required. If you are accessing string values from TempData, typecast is not required. But it is mandatory to typecast explicitly to the actual type if you are accessing data other than the string type from the TempData.
Example to Understand TempData in ASP.NET Core MVC Application
We will use the same application we worked on in our previous article. Modify the HomeController as shown below to use TempData. As you can see, here, we have created three action methods. In the Index action method, we have set the Name and Age values using TempData; and in the other two action methods, we are not doing anything.
using Microsoft.AspNetCore.Mvc; namespace FirstCoreMVCWebApplication.Controllers { public class HomeController : Controller { public ActionResult Index() { TempData["Name"] = "Pranaya"; TempData["Age"] = 30; return View(); } public ActionResult Privacy() { return View(); } public ActionResult About() { return View(); } } }
Next, modify the Index, Privacy and add the About Views within the Home Folder, which is inside the Views folder as follows:
Index.cshtml
@{ ViewData["Title"] = "Index Page"; } <div class="text-left"> <b>Name:</b> @TempData["Name"] <br /> <b>Age:</b> @TempData["Age"] </div>
Privacy.cshtml
@{ ViewData["Title"] = "Privacy Policy"; } <div class="text-left"> <b>Name:</b> @TempData["Name"] <br /> <b>Age:</b> @TempData["Age"] </div>
About.cshtml
@{ ViewData["Title"] = "About Page"; } <div class="text-left"> <b>Name:</b> @TempData["Name"] <br /> <b>Age:</b> @TempData["Age"] </div>
If you look at the implementation of all these three methods, the implementation is the same, i.e., from each view are accessing the TempData values.
Now, run the application and visit the Index Page, and you will get the data as expected, as shown in the below image.
Now, if you visit Privacy and About, you will not get the data as expected, as shown in the image below.
Why are we not getting the TempData value in the next subsequent Request?
The reason is once we read the value from TempData, then the TempData key is going to be deleted from the TempData dictionary collection. And this is the default behavior of TempData. In our example, within the Index View, we are reading the TempData, and hence after reading the Age and Name keys from TempData, these two keys are going to be deleted from the TempData dictionary collection.
How to Retain the TempData value in the next Sub Sequent Request in ASP.NET Core MVC?
We can retain the TempData values for the next subsequent request in many ways. Let us discuss them one by one.
Method1: Don’t Fetch the Data from TempData
If we don’t fetch the data from the TempData in either Index Action Method or from the Index View, then the Tempdata will be preserved in the TempData dictionary collection and can be accessed from the next subsequent request. To do so, let us modify the Index.cshtml view as follows. As you can see, we are only fetching the Age key from Tempdata, not the Name key, which means the Name key will be preserved in the TempData dictionary collection for the next request.
@{ ViewData["Title"] = "Index Page"; } <div class="text-left"> <b>Name:</b> <br /> <b>Age:</b> @TempData["Age"] </div>
Now, run the application, visit the Index page, and then visit either the Privacy or About Page, as shown in the image below. You can see, Age value is on Index Page, and Name value is on the Privacy Page.
Now, if you visit the About page, you will not see any data shown in the image below.
Method2: Use the Keep Method to Preserve the Data in TempData
If we want to preserve the TempData for the next request, we can use TempData Keep Method. In this case, no matter whether you access the data from the TempData.
In order to retain the TempData value in the consecutive request, we need to call the Keep() method. There are two overloaded versions available for the Keep method in the ITempDataDictionary interface, as follows:
- Keep(): Marks all keys in the dictionary for retention. That means if you want to retain the values of all the keys, you need to use this overloaded version.
- Keep(string key): Marks the specified key in the dictionary for retention. That means if you want to retain the values of a particular key, then you need to use this overloaded version, and, in this case, you need to pass the string key as a parameter to this method.
For a better understanding, please modify the Home Controller as follows. Here, you can see inside the Index Action method, and we are calling the Keep method.
using Microsoft.AspNetCore.Mvc; namespace FirstCoreMVCWebApplication.Controllers { public class HomeController : Controller { public ActionResult Index() { TempData["Name"] = "Pranaya"; TempData["Age"] = 30; //Retention of All keys of TempData for the next request //TempData.Keep(); //Retention of Individual keys of TempData for the next request TempData.Keep("Name"); TempData.Keep("Age"); return View(); } public ActionResult Privacy() { return View(); } public ActionResult About() { return View(); } } }
Next, modify the Index.cshtml view as follows. As you can see, here we are fetching both keys from TempData Dictionary Collection.
@{ ViewData["Title"] = "Index Page"; } <div class="text-left"> <b>Name:</b> @TempData["Name"] <br /> <b>Age:</b> @TempData["Age"] </div>
Now, run the application, visit the Index page, and then visit either the Privacy or About Page, as shown in the image below. You can see both Index Page and Privacy Page showing both Name and Age values.
Now, if you visit the About page, you will not see any data shown in the image below.
How to Preserve the TempData for the About Page?
In that case, we need to call the TempData.Keep method inside the Privacy Action method. So, modify the Home Controller as follows:
using Microsoft.AspNetCore.Mvc; namespace FirstCoreMVCWebApplication.Controllers { public class HomeController : Controller { public ActionResult Index() { TempData["Name"] = "Pranaya"; TempData["Age"] = 30; //Retention of All keys of TempData for the next request //TempData.Keep(); //Retention of Individual keys of TempData for the next request TempData.Keep("Name"); TempData.Keep("Age"); return View(); } public ActionResult Privacy() { //Retention of Individual keys of TempData for the next request TempData.Keep("Name"); TempData.Keep("Age"); return View(); } public ActionResult About() { //Retention of Individual keys of TempData for the next request //TempData.Keep("Name"); //TempData.Keep("Age"); return View(); } } }
Method3: Using TempData Peek Method
By default, when we read the key from TempData, then after reading the value, the key is going to be deleted from the TempData Dictionary Collection. So, instead of reading the values using string Indexer, we can also read the data from TempData using the Peek method, and to this method, we need to pass the key name. In this case, it will read the data but will preserve the key for the next subsequent request.
To Understand this concept, please modify the Home Controller class as follows. Here, inside the Index Action method, we store the data in TempData and redirect the request to the Privacy Action Method. As the Index View is not executed, we are fetching the data from the TempData. So, these TempData keys are available for the next request, which is, in this case, the Privacy Action method. We are fetching the data from the Privacy action method using the Peek method, which will return the data and keep the keys alive for the next request. And inside the About Page, we can access the value.
using Microsoft.AspNetCore.Mvc; namespace FirstCoreMVCWebApplication.Controllers { public class HomeController : Controller { public ActionResult Index() { TempData["Name"] = "Pranaya"; TempData["Age"] = 30; //We are redirecting the request to Privacy Action Method from here //In this case, Index View is not going to be executed //Means we are not reading the TempData keys and hence they available //in the Privacy Action method //return RedirectToAction("Privacy", " Home"); return RedirectToAction("Privacy"); } public ActionResult Privacy() { //Retention of Individual keys of TempData for the next request if(TempData.ContainsKey("Name")) { //Peek Method will read the data and preserve the key for next request ViewData["Name"] = TempData.Peek("Name"); } if (TempData.ContainsKey("Age")) { //Peek Method will read the data and preserve the key for next request ViewData["Age"] = TempData.Peek("Age"); } return View(); } public ActionResult About() { return View(); } } }
Modifying Privacy,cshtml view:
Inside the Privacy,cshtml View, we need to use ViewData instead of Tempdata as follows:
@{ ViewData["Title"] = "Privacy Policy"; } <div class="text-left"> <b>Name:</b> @ViewData["Name"] <br /> <b>Age:</b> @ViewData["Age"] </div>
With the above changes in place, run the application and see if everything is working as expected. So, when you run the application, the Index action method will be redirected to the Privacy Action method. Then if you visit the About action method, you will also get the data as expected, as shown in the image below.
A few important points to note about TempData:
- Lifetime: TempData data persists across a single redirect. Once the data is read, it’s removed from TempData.
- Persistence: TempData is typically stored in a session state, which means it incurs some storage and performance overhead associated with sessions.
- Keys: Keys used to store and retrieve data in TempData should be strings. You should use consistent and unique keys to avoid conflicts.
- Type Conversion: TempData stores data as objects, so you need to cast it back to the appropriate type when retrieving.
- Limited Use: TempData is meant for small amounts of data, like messages or small objects, and not for large datasets.
- Not for AJAX Requests: TempData is not suitable for AJAX requests as it’s based on server-side redirects.
Remember that TempData is best used for short-lived data that needs to be retained only for the next request. If you need to store data for a longer duration, consider using other mechanisms like session state, cookies, or a database.
In the next article, I am going to discuss Routing in ASP.NET Core MVC Applications with Examples. Here, in this article, I try to explain the TempData in ASP.NET Core MVC Application with Examples. I hope you enjoy this ASP.NET Core MVC TempData with Examples article.