TempData in ASP.NET Core MVC

SPONSOR AD

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 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 using TempData. As part of this article, we are going to discuss the following pointers, which are related to MVC TempData.

  1. Why do we need TempData in the ASP.NET Core MVC Application?
  2. What exactly is TempData in ASP.NET Core MVC?
  3. How to use TempData?
  4. How do you Pass and Retrieve data from TempData?
  5. How do you retain TempData values in the Consecutive Request in ASP.NET Core MVC?
  6. How do you Store a Complex Object in TempData in ASP.NET Core MVC?
  7. What are the advantages and disadvantages of TempData in ASP.NET Core MVC?
  8. When should you use 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. For example, we may need to pass the data from one controller to another, from one action method to another action method within the same controller, or to a different controller. Then, in such situations like this, we need to use TempData in the 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 want 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 read or after the subsequent request is processed.

SPONSOR AD

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.

What is TempData in ASP.NET Core MVC?

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.

Why do we need TempData in the ASP.NET Core MVC Application?

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 we pass to the dictionary will be stored as an object type.

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

SPONSOR AD
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, we 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.

How to Pass and Retrieve Data From TempData in ASP.NET Core MVC?

Now, if you visit Privacy and About, you will not get the data as expected, as shown in the image below.

Example to Understand TempData in ASP.NET Core MVC Application

Why are we not getting the TempData value in the next subsequent Request?

The reason is that once we read the value from TempData, the TempData key will be deleted 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 you 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

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

SPONSOR AD
@{
    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.

Why are we not getting the TempData value in the next subsequent Request?

Now, if you visit the About page, you will not see any data shown in the image below.

How to Retain the TempData value in the next Sub Sequent Request in ASP.NET Core MVC?

Method 2: Use the Keep Method to Preserve the Data in TempData

If we want to preserve the TempData for the next request, we can use the TempData Keep Method. In this case, no matter whether you access the data from the TempData.

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:

  1. 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.
  2. 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, which 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. You can see both the Index Page and Privacy Page showing both Name and Age values.

Use the Keep Method to Preserve the Data in TempData in ASP.NET Core MVC

SPONSOR AD

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?

How do you 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

By default, after reading the key from TempData, the key will 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. 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.

Using TempData Peek Method

How do you Store a Complex Object in TempData in ASP.NET Core MVC?

To retain a complex object in TempData in ASP.NET Core MVC, you need to serialize the object to a string format, typically JSON, and then deserialize it back when retrieving it. TempData is a key-value pair dictionary and is typically used to store data that needs to persist across a single redirect.

Serialize the Object to JSON
Before storing the complex object in TempData, you must convert it to a JSON string. This is because TempData can only store primitive types by default. You can use System.Text.Json.JsonSerializer or Newtonsoft.Json (aka JSON.NET) for serialization. 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 back to the original object type. The following is the syntax.

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 following is the syntax.

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.

TempData Load() and Save() Method in ASP.NET Core MVC:

TempData Load() Method: The Load() method is used to load the TempData dictionary from the temp data provider. It is generally not necessary to call Load() explicitly because ASP.NET Core automatically calls it before the TempData property is accessed for the first time in an action method or Razor page.

TempData Save() Method: The Save() method saves the TempData dictionary to the temp data provider. Similar to Load(), it’s generally not necessary to call Save() explicitly. ASP.NET Core automatically calls Save() at the end of a request to persist data if there were any changes to the TempData dictionary.

The following example shows how you can use the Load() and Save() methods with TempData in an ASP.NET Core MVC application.

using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
    public IActionResult Index()
    {
        // Store a message in TempData
        TempData["Message"] = "Hello from Index!";

        // Redirect to another action
        return RedirectToAction("About");
    }

    public IActionResult About()
    {
        // Ensure TempData is loaded
        TempData.Load();

        // Retrieve the data
        var message = TempData["Message"] as string;

        // Save TempData for the next request if needed
        TempData.Save();

        // Pass the message to the view
        ViewBag.Message = message;

        return View();
    }
}

Here,

  • TempData.Load(): This explicitly loads TempData from the data store, which is useful when you want to read the contents early in the request lifecycle.
  • TempData.Save(): This saves the TempData for the next request. TempData is typically marked for deletion after it’s read, so calling Save() after reading a value ensures that it persists for another request.

Modify About.cshtml view as follows:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>About</title>
</head>
<body>
    @ViewBag.Message
</body>
</html>
Advantages of TempData in ASP.NET Core MVC:
  • Maintains Data After Redirects: TempData is designed to transfer data from one request to another, making it ideal for scenarios like showing success or error messages after a form submission and subsequent redirect.
  • Ease of Use: TempData is easy to use and implement. It provides a straightforward way to pass data between controllers and views without complex implementations.
  • Automatic Cleanup: TempData automatically removes information after it’s read in the next request, which helps in managing the lifecycle of the data and prevents stale data issues.
  • Uses Session State: TempData uses session state, which means it can store various data types and is not limited to simple data.
  • Flexibility: TempData can be used in various scenarios where data needs to be preserved for more than a single request but not permanently.
Disadvantages of TempData in ASP.NET Core MVC:
  • Limited Lifetime: TempData is designed to keep data for a very short period (until it’s read in a subsequent request). This makes it unsuitable for data that needs to be persistent across multiple requests over a longer period.
  • Dependency on Session State: TempData relies on session state, which can be a drawback if session state is disabled or if you’re trying to avoid using session state for scalability reasons.
  • Potential for Data Loss: Since TempData relies on session state and cookies, there’s a risk of data loss if the client’s browser does not support cookies or if the cookies are cleared.
  • Not Suitable for Large Data: TempData is not ideal for transferring large amounts of data because it can affect performance and increase the load on server memory.
  • Risk of Overusing: TempData can be misused for purposes it’s not intended for, like passing data that should be stored in a database or managed through view models.
  • Security Concerns: Since TempData may use cookies, sensitive data should not be stored in it unless it’s encrypted to prevent potential security risks.
When should you use TempData in ASP.NET Core MVC?

TempData in ASP.NET Core MVC is used to store data temporarily. It is useful in scenarios where data needs to be preserved for a short duration, typically from one request to the next. The most common use cases include:

  • Passing Data Between Actions: TempData is often used to pass data between different actions in a controller or between different controllers. For instance, you might want to redirect to a new action after performing some operation and show a success or error message. TempData can hold this message until it’s read in the next request.
  • Storing One-Time Messages: TempData is suitable for storing one-time messages like error, success, or notification messages. After the data is read, it is deleted, which makes it perfect for flash messages that need to persist only until the next request.
      • Success Messages: After successfully submitting a form or completing an operation.
      • Error Messages: When an operation fails, you want to redirect the user but still show a message about what went wrong.
      • Informational Alerts: Informing users about system updates, temporary outages, or other transient states.
  • Conditional Data Transfer: TempData can be useful when transferring data between requests conditionally. For example, suppose an operation in one action leads to a decision to redirect to one of several other actions. In that case, TempData can be used to pass necessary data based on the condition.
  • Error Handling: When handling errors, TempData can be used to store error details temporarily and display them on an error view or error page after a redirect.
  • Storing Short-Term State: While TempData is not meant for extensive state management, it can be useful for storing temporary states only needed in the next request, such as intermediate steps in a multi-step process or wizards.
When Not to Use TempData?

While TempData can be beneficial in the above scenarios, it’s crucial to recognize when not to use it:

  • Long-Term Persistence: If you need to store data across multiple requests or sessions, other mechanisms like session state, cookies, or databases are more appropriate.
  • Sensitive Information: Since the default provider for TempData is cookie-based, storing sensitive data can pose security risks, even if the data is encrypted.
  • Large Data: Due to the cookie size limitation, it’s not suitable for storing large data sets or objects.

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 ASP.NET Core MVC TempData with Examples article.

SPONSOR AD

Leave a Reply

Your email address will not be published. Required fields are marked *