Back to: ASP.NET Core Tutorials For Beginners and Professionals
TempData in ASP.NET Core MVC
In this article, I will discuss ASP.NET Core MVC TempData with Examples. As discussed in our previous articles, we can use ViewData, ViewBag, and Strongly Typed Models to pass data from a controller action method to a view. Now, we will see another approach to sending data from the controller action method to a view, i.e., TempData. As part of this article, we will discuss the following pointers 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 Do We Use TempData in ASP.NET Core MVC?
- How do you Pass and Retrieve data from TempData?
- How do you retain TempData values in the Consecutive Request in ASP.NET Core MVC?
- How do you Store a Complex Object in TempData in ASP.NET Core MVC?
Why do we need TempData in the ASP.NET Core MVC Application?
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. Then, in such situations like this, we need to use TempData in the ASP.NET Core MVC Application.
TempData in ASP.NET Core MVC serves the purpose of passing data from one request to the next, specifically between actions or redirects. The following are some of the common use cases of TempData in ASP.NET Core MVC Applications:
- Passing Data After Redirects: TempData helps to pass data after redirects, a common requirement in web applications where a method performs operations and redirects to another method.
- Storing Temporary Data: It is useful for storing temporary data that does not need to be persisted in the database but must be available across requests.
- Message Passing: Commonly used for displaying success or error messages on action redirects, especially in post-redirect-get patterns.
What is TempData in ASP.NET Core MVC?
TempData in ASP.NET Core MVC Application is one of the mechanisms for passing 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. It uses session storage to persist data across requests, ensuring data is available after a redirect. TempData is cleared after it is read, making it suitable for temporary data that doesn’t need to persist beyond a single request cycle. If you go to the Controller class, you will see the following signature for the TempData.
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 TempData in ASP.NET Core MVC is a dictionary object. As a dictionary object, it stores data in the form of key-value pairs, where each key must be a string. The value we pass to the dictionary will be stored as an object type. Here, you can also see that to manage the TempData value in ASP.NET Core MVC, it provides 5 methods. The use of these methods is as follows:
Load and Save:
These methods are primarily used by the ASP.NET Core framework to handle the lifecycle of TempData. Developers usually do not need to call these methods directly.
- Load: The Load method loads the TempData values from the current HTTP context. The framework typically invokes this method internally, and it is not commonly used directly in application code.
- Save: The Save method is used to save the current state of TempData into the current HTTP context. It’s typically called automatically by the ASP.NET Core framework at the end of a request, ensuring that any changes made to TempData during the request are persisted for the next request.
Keep:
The Keep method marks all items in TempData to be retained for the next request. This method is useful to ensure that TempData is not cleared after reading.
Keep(string key):
This method retains a specific item in TempData for another request. It is useful when we have multiple items in TempData but only need to preserve some of them. Only the TempData entry with the specified key will be preserved for the next request, while others will be discarded.
Peek(string key)
This method reads an item from TempData without removing it. This is useful when we need to access the same TempData item across multiple requests or in multiple places within the same request. Unlike reading TempData using the String Indexer, which marks the item for deletion, Peek allows the data to be read and still remain in TempData for further requests.
How do you 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 as 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. However, it is mandatory to typecast explicitly to the actual type if you are accessing data other than the string type from the TempData.
- Passing Data: Set values in TempData using TempData[“Key”] = value; in one action.
- Retrieving Data: Access values from TempData using var value = TempData[“Key”] as Type; in another action.
Example to Understand TempData in ASP.NET Core MVC Application
We will use the same application we have worked on so far. Please modify the HomeController to use TempData, as shown below. As you can see, we have created three action methods here. 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>
The implementation of all three methods is the same. From each view, we access the TempData values using the String Indexer, i.e., using the string key name. Now, run the application and visit the Index Page, and you will get the data as expected, as shown in the image below.
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 that once we read the value from TempData using the String Indexer, it will mark the item for deletion from the TempData dictionary collection. And this is the default behavior of TempData. In our example, we are reading the TempData within the Index View. Hence, after reading the Age and Name keys from TempData, these two keys will be deleted from the TempData dictionary collection.
How Do We 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.
Method 1: Don’t Fetch the Data from TempData
If we don’t fetch the data from the TempData either from the Index Action Method or from the Index View. In that case, 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 that the age value is on the index page, and the name value is on the Privacy page.
If you visit the About page, you will not see the data shown in the image below.
Method 2: Use the Keep Method to Preserve the Data in TempData
To preserve the TempData for the next request, use the TempData Keep or Keep(string) Method. In this case, no matter whether you access the data or not from the TempData, it will preserve the TempData value for the next request. The Keep() method will Mark all keys in the dictionary for retention. On the other hand, the Keep(string key) method marks the specified key in the dictionary for retention. To better understand, please modify the Home Controller as follows. Here, you can see inside the Index Action method we call 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, we are fetching both keys from the 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. Both the Index Page and Privacy Page show the Name and Age values.
If you visit the About page, you will not see the data shown in the image below.
How Do We Preserve the TempData for the About Page?
In that case, we need to call the 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(); } } }
Method 3: Using TempData Peek Method
The key will be deleted from the TempData Dictionary Collection by default if we read the data using the string Indexer. So, instead of reading the values using the string Indexer, we can also read the data from TempData using the Peek method. To do this, we need to pass the key name to the Keep method. In this case, it will read the data but preserve the key for the next subsequent request.
To Understand this concept, please modify the Home Controller class as follows. 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 not 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, run the application and see if everything works 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.
How Do We Store a Complex Object in TempData in ASP.NET Core MVC?
To store a complex object in TempData in ASP.NET Core MVC, we need to serialize it to a string format, typically JSON, and then deserialize it when retrieving it.
Serialize the Object to JSON
Before storing the complex object in TempData, we must convert it to a JSON string. This is because TempData can only store primitive types. For serialization, you can use System.Text.Json.JsonSerializer, or Newtonsoft.Json. The following is the syntax.
var myObject = new MyComplexObject(); string json = JsonSerializer.Serialize(myObject); TempData["MyObject"] = json;
Retrieve and Deserialize the Object
When retrieving the object, get the JSON string from TempData and deserialize it to the original object type. The syntax is as follows.
if (TempData["MyObject"] is string json) { var myObject = JsonSerializer.Deserialize<MyComplexObject>(json); // Use myObject as needed }
Handling TempData Persistence
If you need the data to persist for another request, you must read it and keep it again. The syntax is as follows.
string json = TempData["MyObject"] as string; TempData.Keep("MyObject"); // This line keeps the data for another request
Creating the Model:
First, create the following Student class within the Models folder.
namespace FirstCoreMVCWebApplication.Models { public class Student { public int StudentId { get; set; } public string? Name { get; set; } public string? Branch { get; set; } public string? Section { get; set; } public string? Gender { get; set; } } }
Modifying the Home Controller:
using FirstCoreMVCWebApplication.Models; using Microsoft.AspNetCore.Mvc; using System.Text.Json; namespace FirstCoreMVCWebApplication.Controllers { public class HomeController : Controller { public ActionResult Index() { //Create the Complex Object var student = new Student() { StudentId = 1, Name = "Pranaya", Gender = "Male", Branch = "CSE", Section = "A" }; //Convert the Complex Object to Json string jsonStudent = JsonSerializer.Serialize(student); //Store the JSON Objec into the TempData TempData["StudentObject"] = jsonStudent; //return RedirectToAction("Privacy", "Home"); return RedirectToAction("Privacy"); } public JsonResult Privacy() { Student? student = new Student(); if (TempData["StudentObject"] is string jsonStudent) { //Deserialize the Json Object to Actual Student Object student = JsonSerializer.Deserialize<Student>(jsonStudent); //You can use the Student // The following line keeps the data for another request TempData.Keep("StudentObject"); } return Json(student); } public JsonResult About() { Student? std = new Student(); if (TempData["StudentObject"] is string jsonStudent) { //Deserialize the Json Object to Actual Student Object std = JsonSerializer.Deserialize<Student>(jsonStudent); } return Json(std); } } }
Now, run the application and test it, and it should work as expected.
How TempData Manage the Data in ASP.NET Core MVC:
ASP.NET Core MVC provides different storage mechanisms for TempData, known as TempData providers. Depending on the configuration and application requirements, TempData can be stored using cookies or a session state.
- Cookie-Based TempData Provider: This provider stores TempData using cookies. The data is serialized into JSON, encoded, and stored as cookies. This method is stateless but limited by the size of cookies and involves sending data back and forth between the server and the client. Please click here to learn about Cookies in ASP.NET Core MVC Applications.
- Session-Based TempData Provider: This provider stores TempData in a session state. It’s server-side and can handle larger amounts of data compared to cookies. However, it requires the application to enable the session state. Please click here to learn about Sessions in ASP.NET Core MVC Applications.
Note: In ASP.NET Core MVC, if we don’t configure any Provider, it will use the Cookie TempData Provider by default.
How TempData Internally Works in ASP.NET Core MVC:
Let us understand how the TempData works in ASP.NET Core MVC:
- Setting TempData: When we set a value in TempData, it is stored in the TempData dictionary. For example, TempData[“Message”] = “Hello, world!”;
- Storing TempData: At the end of the request, the TempData dictionary is serialized and stored in the session or cookie by the Save method.
- Loading TempData: At the beginning of the next request, TempData is deserialized from the session by the Load method, making it available for the current request.
- Reading TempData: When you read a value from TempData, it is marked for deletion but not immediately removed. This ensures it can still be retained for the next request if needed. For example, var message = TempData[“Message”] as string;
- Retaining TempData: If you want to keep TempData values for another request, use the Keep or Peek methods. These methods ensure that TempData items are not marked for deletion.
In the next article, I will discuss the Post-Redirect-Get (PRG) Pattern Example in the ASP.NET Core MVC Application with Examples. In this article, I try to explain TempData in the ASP.NET Core MVC Application with examples. I hope you enjoy this article on ASP.NET Core MVC TempData with Examples.