TempData in ASP.NET Core MVC

TempData in ASP.NET Core MVC

In this article, I will discuss ASP.NET Core MVC TempData with Examples. When building web applications using ASP.NET Core MVC, managing data between requests is a common challenge. While ViewData and ViewBag help transfer data from a controller to a view during a single request, sometimes you need to persist data across multiple requests, especially during redirects. This is where TempData comes into play.

What is TempData in ASP.NET Core MVC?

TempData is a dictionary object provided by ASP.NET Core MVC that stores data temporarily until it is read. It allows data to persist from one HTTP request to the next, making it ideal for passing data during redirects.

  • It stores data in key-value pairs, where the key is a string and the value is of object type. This allows us to store any type of data, including null values.
  • Data in TempData persists only until it is read or until a subsequent HTTP request is made. Once read, it is automatically removed.
  • It is specifically useful when you need to transfer small amounts of data between actions or views, for example, after form submissions with redirects.
Why Do We Need TempData in ASP.NET Core MVC?

There are scenarios in web applications where you need to pass data from one action to another, especially after a redirect. For example:

  • After submitting a form (POST), you want to display a confirmation message on a GET action (PRG Pattern: Post-Redirect-Get).
  • Passing error/success messages between controllers or actions after some processing.
  • Avoid passing data in query strings or hidden form fields for short-lived data.
  • Temporary status data or flags that should be available only for one subsequent request.

ViewBag and ViewData cannot be used for this, because they don’t persist across redirects. TempData fills this gap by retaining its data until it is read in the subsequent request.

Understanding TempData Methods: Load, Save, Keep, and Peek

If you go to the Controller class, you will see the following signature for the TempData.

What is TempData in ASP.NET Core MVC?

As you can see in the image above, the data type of TempData is ITempDataDictionary. Now, if you go to the definition of the ITempDataDictionary class, you will see the following.

Why Do We Need TempData in ASP.NET Core MVC?

As you can see in the image above, ASP.NET Core MVC provides five methods for managing the TempData value. Let us understand the use of each method in ASP.NET Core MVC.

Load and Save Methods

These methods are rarely used directly in normal controller code. They are used internally by the framework:

  • Load: Loads TempData from the session or cookies at the start of a request.
  • Save: Saves TempData to the session or cookies at the end of a request, if there’s still data remaining.

Under the hood, TempData uses either cookies or the session to store its data, depending on your configuration. By default, it uses cookies.

Keep() and Keep(string key)

By default, the TempData in ASP.NET Core MVC is designed to remove data after it is read, but sometimes you may want to keep data for more than one request. That’s where Keep() and Keep(string key) come into play:

  • Keep(): Marks all items in TempData for retention for another request, so nothing gets removed.
  • Keep(string key): Marks a specific key to retain its value for another request, instead of everything.
Peek(string key)

Allows you to read the value of a specific TempData key without marking it for deletion. In other words, you get the value, but it is still available for the next request.

How Do You Pass and Retrieve Data from TempData in ASP.NET Core MVC?

The most important point to remember is that it stores the data as an object, so when retrieving the data from TempData, type casting is required. If you are accessing string values from TempData, type casting is not necessary. 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 to TempData:

In your controller action, you can assign values to TempData using keys:

Passing Data to TempData

Retrieving Data from TempData:

In the action or view that receives the redirect, you can access the TempData value:

Retrieving Data from TempData

In the Razor view, you can access it like:

How Do You Pass and Retrieve Data from TempData in ASP.NET Core MVC?

Retaining Data for Subsequent Requests:

To retain the value for subsequent requests, use the Peek or Keep method:

Retaining Data for Subsequent Requests

Example to Understand TempData in ASP.NET Core MVC

We want to develop a Product Management system that enables users to add new products through a user-friendly form. After successfully adding a product (via POST), we need to redirect the user to the product list page (GET) and show a success notification message. TempData is perfect for this scenario because it lets us pass the success message across the redirect.

Step 1: Set up an ASP.NET Core MVC Project

Start by creating a new ASP.NET Core Web Application using the MVC template:

  • Project name: TempDataDemo
  • Choose ASP.NET Core Web App (Model-View-Controller) as the template
  • This gives you the basic MVC structure: Models, Views, and Controllers folders
Step 2: Create the Product Model

Create a class file named Product.cs under the Models folder, then copy and paste the following code. This class defines the properties of a product, including validation attributes for form input. Validation ensures user inputs are checked before processing. CreatedDate tracks when the product was added.

using System.ComponentModel.DataAnnotations;

namespace TempDataDemo.Models
{
    public class Product
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "Product name is required.")]
        [StringLength(100)]
        public string Name { get; set; } = null!;

        [StringLength(500)]
        public string? Description { get; set; }

        [Range(0, 1000000, ErrorMessage = "Price must be a positive value.")]
        public decimal Price { get; set; }

        [Range(0, int.MaxValue, ErrorMessage = "Stock cannot be negative.")]
        public int Stock { get; set; }

        [Display(Name = "Created Date")]
        public DateTime CreatedDate { get; set; }
    }
}
Step 3: Create In-Memory Product Repository

For demo purposes, products are stored in a static list in memory. So, create a class file named ProductRepository.cs within the Models folder, then copy and paste the following code. The GetAll() method returns the current list of products, and the Add() method adds a new product with an auto-generated ID and the current date.

namespace TempDataDemo.Models
{
    public static class ProductRepository
    {
        private static List<Product> _products;

        static ProductRepository()
        {
            _products = new List<Product>
            {
                new Product { Id = 1, Name = "Apple iPhone 14", Price = 79900m, Description = "Latest Apple iPhone with A15 chip", Stock = 25, CreatedDate = DateTime.Now.AddDays(-30) },
                new Product { Id = 2, Name = "Samsung Galaxy S23", Price = 69999m, Description = "Flagship Samsung phone with great camera", Stock = 40, CreatedDate = DateTime.Now.AddDays(-20) },
                new Product { Id = 3, Name = "OnePlus 11", Price = 55999m, Description = "Powerful OnePlus device with fast charging", Stock = 30, CreatedDate = DateTime.Now.AddDays(-10) }
            };
        }

        public static List<Product> GetAll()
        {
            return _products;
        }

        public static void Add(Product product)
        {
            product.Id = _products.Max(p => p.Id) + 1;
            product.CreatedDate = DateTime.Now; 
            _products.Add(product);
        }
    }
}
Step 4: Create ProductController

Create an empty MVC controller named ProductController within the Controllers folder, then copy and paste the following code. This controller handles listing products and creating new ones.

using Microsoft.AspNetCore.Mvc;
using TempDataDemo.Models;

namespace TempDataDemo.Controllers
{
    public class ProductController : Controller
    {
        // GET: /Product
        public IActionResult Index()
        {
            // Retrieve all products
            var products = ProductRepository.GetAll();

            // Pass TempData message to ViewBag to display if exists
            ViewBag.SuccessMessage = TempData["SuccessMessage"];

            return View(products);
        }

        // GET: /Product/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: /Product/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Product product)
        {
            if (ModelState.IsValid)
            {
                // Add product to repository
                ProductRepository.Add(product);

                // Set success message in TempData
                TempData["SuccessMessage"] = $"Product '{product.Name}' created successfully!";

                // Redirect to Index (GET)
                return RedirectToAction(nameof(Index));
            }

            // If validation fails, show form again with errors
            return View(product);
        }
    }
}
Code Explanation:
  • The POST action stores the success message in TempData.
  • After adding the product, it redirects to the Index action.
  • The Index action retrieves the TempData message and passes it to the view.
Step 5: Create Views

First, create a folder named ‘Product’ within the ‘Views’ folder, where we will create views related to the Product controller.

Index.cshtml View

Add a view named Index.cshtml within the Views/Product and copy and paste the following code. This view displays the Product List and the Success Message.

@model List<TempDataDemo.Models.Product>

@{
    ViewData["Title"] = "Product List";
}

<div class="container mt-4">
    <h2 class="mb-4">Product List</h2>

    @if (!string.IsNullOrEmpty(ViewBag.SuccessMessage))
    {
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <strong>Success!</strong> @ViewBag.SuccessMessage
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    }

    <table class="table table-striped table-bordered">
        <thead class="table-dark">
            <tr>
                <th style="width: 5%;">ID</th>
                <th>Name</th>
                <th>Description</th>
                <th style="width: 10%;">Price (₹)</th>
                <th style="width: 10%;">Stock</th>
                <th style="width: 15%;">Created Date</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var product in Model)
            {
                <tr>
                    <td>@product.Id</td>
                    <td>@product.Name</td>
                    <td>@product.Description</td>
                    <td>@product.Price.ToString("N2")</td>
                    <td>@product.Stock</td>
                    <td>@product.CreatedDate.ToString("dd MMM yyyy")</td>
                </tr>
            }
        </tbody>
    </table>

    <a class="btn btn-primary" href="@Url.Action("Create")">Create New Product</a>
</div>
Create.cshtml View (Product Creation Form)

Add a view named Create.cshtml within the Views/Product and copy and paste the following code.

@model TempDataDemo.Models.Product

@{
    ViewData["Title"] = "Create Product";
}

<div class="container mt-4">
    <h2 class="mb-4">Create Product</h2>

    <form asp-action="Create" method="post" class="needs-validation" novalidate>
        <div class="mb-3">
            <label asp-for="Name" class="form-label"></label>
            <input asp-for="Name" class="form-control" />
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>

        <div class="mb-3">
            <label asp-for="Description" class="form-label"></label>
            <textarea asp-for="Description" class="form-control" rows="3"></textarea>
            <span asp-validation-for="Description" class="text-danger"></span>
        </div>

        <div class="mb-3">
            <label asp-for="Price" class="form-label"></label>
            <input asp-for="Price" class="form-control" />
            <span asp-validation-for="Price" class="text-danger"></span>
        </div>

        <div class="mb-3">
            <label asp-for="Stock" class="form-label"></label>
            <input asp-for="Stock" class="form-control" type="number" min="0" />
            <span asp-validation-for="Stock" class="text-danger"></span>
        </div>

        <button type="submit" class="btn btn-success">Create</button>
        <a class="btn btn-secondary ms-2" href="@Url.Action("Index")">Back to List</a>
    </form>
</div>
Making the Index View of Product Controller the Home Page:

Please modify the Program class as follows:

namespace TempDataDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            //Configuring Product Controller Index Action Method as Home Page
            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Product}/{action=Index}/{id?}");

            app.Run();
        }
    }
}
Running the Application:

When you run the application, it will display the following Index Page of the Product controller.

Example to Understand TempData in ASP.NET Core MVC

Once you click on the Create a New Product button, it will open the following Product Create Page. Please fill out the form by providing valid product information, then click the Create button.

TempData in the ASP.NET Core MVC Application with examples

Now, once you click on the Create button, it will submit a request to the server. The server will create a new product with the submitted form data, store a success message in the TempData, and then redirect to the Index page. In the Index page, you will see the newly added Product and the success message that you set in the TempData, as shown in the image below.

How TempData Manages the Data in ASP.NET Core MVC

How TempData Manages 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 exchanging data between the server and the client.
  • 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.

Note: In ASP.NET Core MVC, if we don’t configure any Provider, it will use the Cookie TempData Provider by default.

How to Configure Session-Based TempData Provider in ASP.NET Core MVC?

Since session state stores data on the server side, it requires some kind of backing store (in-memory by default). If you are running in a load-balanced environment, configure a distributed cache or session store (e.g., Redis, SQL Server) to ensure sessions work correctly.

Using session-based TempData is good when you want to avoid storing TempData in client cookies (which can get large or reveal sensitive data). To Configure Session-Based TempData, please modify the Program class as follows:

using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace TempDataDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            // Add session support
            builder.Services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(20);  // Session timeout (adjust as needed)
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;  // Required for GDPR compliance if tracking cookies are disabled
            });

            // Replace default TempData provider with session-based TempData provider
            builder.Services.AddSingleton<ITempDataProvider, SessionStateTempDataProvider>();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            // Use session middleware before MVC middleware
            app.UseSession();

            app.UseRouting();

            app.UseAuthorization();

            //Configuring Product Controller Index Action Method as Home Page
            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Product}/{action=Index}/{id?}");

            app.Run();
        }
    }
}
Explanation of Key Points:
  • AddSession(): This enables ASP.NET Core session support.
  • AddSingleton<ITempDataProvider, SessionStateTempDataProvider>(): Replaces the default cookie-based TempData provider with the session-based provider.
  • UseSession(): Adds the session middleware to the pipeline; it must be called before UseRouting and MVC middleware so that the session is available in controllers.
  • Session Timeout: IdleTimeout controls how long the session data is retained if the user is inactive.

TempData is an essential feature in ASP.NET Core MVC for temporarily storing data between HTTP requests, especially during redirects. It is useful for scenarios such as displaying success or error messages, passing small pieces of data, and handling short-lived state without relying on sessions or query strings. Understanding TempData’s lifecycle, methods like Keep and Peek, and proper handling of complex data structures empowers developers to create efficient and user-friendly MVC applications.

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 aim to explain TempData in ASP.NET Core MVC Applications with examples. I hope you enjoy this article on ASP.NET Core MVC TempData with Examples.

Registration Open – Microservices with ASP.NET Core Web API

New Batch Starts: 7th July 2025
Session Time: 6:30 AM – 8:00 AM IST

Advance your career with our expert-led, hands-on live training program. Get complete course details, the syllabus, registration, and Zoom credentials for demo sessions via the links below.

Contact: +91 70218 01173 (Call / WhatsApp)

Leave a Reply

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