skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

TempData in ASP.NET Core: Use the [TempData] Attribute

Learn how TempData works in ASP.NET Core and how the [TempData] attribute replaces magic strings in MVC controllers and Razor Pages, with Keep, Peek and FAQ.

6 min read Updated

TempData in ASP.NET Core is a short-lived, per-user dictionary that survives exactly one redirect, which makes it the standard way to pass a message or ID from a POST handler to the next GET. The [TempData] attribute lets you read and write those values through a plain property instead of TempData["magic-string"].

Updated November 2026 for .NET 10 and nullable reference types.

In a previous post, I wrote about solving the form resubmission confirm issue that many developers run into when building web applications. TempData is the tool that makes that pattern work, and the [TempData] attribute is the cleanest way to use it.

What is TempData in ASP.NET Core?

TempData is a dictionary-like store (ITempDataDictionary) that holds a value for the next request made by the same user. By default, a value is removed once you read it, so it is ideal for one-time messages such as “Your order was saved”. Values are isolated per user, so one client never sees another client’s TempData.

It is available in MVC controllers, Razor Pages, and Razor Page models. Each value is stored under a key and comes back as an object, so you have to cast it.

var value = TempData["my-awesome-key"] as string;

More can be read about TempData in the Microsoft Learn docs.

How do I use the TempData attribute?

Decorate a public property on a controller, Razor Page model, or page with [TempData]. ASP.NET Core loads the value from TempData when the property is populated and saves it back when the request finishes, so assigning the property is the same as writing to TempData. Here is a Razor Page model.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace MyApp.Pages;
public class IndexModel : PageModel
{
[TempData]
public string? Name { get; set; }
public void OnGet()
{
if (string.IsNullOrEmpty(Name))
{
Name = "Who are you?";
}
}
public RedirectToPageResult OnPost()
{
Name = "Khalid Abuhakmeh";
return RedirectToPage();
}
}

Note that Name is a string? and that we decorated it with the TempData attribute. When the ASP.NET Core pipeline creates our page model, it detects the attribute and sets the value of our property. The property is nullable because on a normal visit there is nothing in TempData.

Now the Razor Page.

@page
@model IndexModel
@{ ViewData["Title"] = "Home page"; }
<div class="text-center">
<h1 class="display-4">@Model.Name</h1>
<form asp-page="Index" method="post">
<button type="submit">Submit</button>
</form>
</div>

When we submit the form, we can see the value update on our web page.

TempDataAttribute usage

The same attribute works on an MVC controller. Set the property before the redirect and read it in the next action.

using Microsoft.AspNetCore.Mvc;
namespace MyApp.Controllers;
public class HomeController : Controller
{
[TempData]
public string? Message { get; set; }
[HttpPost]
public IActionResult Save()
{
Message = "Saved!";
return RedirectToAction(nameof(Show));
}
public IActionResult Show() => View(model: Message);
}

We can also alter the key that provides value for our property.

[TempData(Key = "Cool")]
public string? Name { get; set; }

And because the key is now just a property name, you no longer risk a typo like TempData["Mesage"] silently returning null.

What does a minimal Program.cs look like?

TempData needs no extra registration for Razor Pages or MVC. AddRazorPages() and AddControllersWithViews() register the default cookie-based provider.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseRouting();
app.MapRazorPages();
app.MapDefaultControllerRoute();
app.Run();

When is a TempData value removed?

A value is marked for deletion once it has been read, and removed at the end of that request. In my testing with the sample above, the Razor Page Name was present on the first GET after the redirect and null on the second GET.

If you need a value to live one request longer, call Keep.

Method What it does
TempData["key"] Reads the value and marks it for deletion
TempData.Peek("key") Reads the value without marking it for deletion
TempData.Keep("key") Retains the value for one more request
TempData.Keep() Retains all values for one more request

In my testing, reading a value and then calling TempData.Keep("key") kept it available for the next request. Peek comes with a catch when you use the attribute. On a key that only TempData["key"] touches, Peek reads the value and leaves it in place. A [TempData] property is different: ASP.NET Core populates it by reading its key through the indexer on every request to that controller or page model, which marks the value for deletion before your code runs. In my testing, a Peek on a key bound to a [TempData] property did not make the value outlive that request, so reach for Keep when you want an attribute-backed value to stick around.

Where does TempData store its data?

ASP.NET Core ships with two providers.

  • Cookie-based (default): the data is serialized into a cookie sent to the browser, which Microsoft Learn notes is encrypted. It needs no server-side state, but cookies have size limits. If you hit them, see ASP.NET Core and chunking HTTP cookies.
  • Session-based: the data lives in session state on the server. Call AddSessionStateTempDataProvider() on the MVC or Razor Pages builder, add AddSession(), and call app.UseSession().
builder.Services.AddSession();
builder.Services.AddControllersWithViews().AddSessionStateTempDataProvider();
builder.Services.AddRazorPages().AddSessionStateTempDataProvider();
var app = builder.Build();
app.UseSession();

I ran the same Razor Page and controller samples against both providers and got identical results.

What types can I store in TempData?

Stick to the short list the default serializer accepts: string, int, bool, DateTime, Guid, enums, collections of int or string, and IDictionary<string, string>. Other numeric types such as long, double, and decimal are not on that list. Both built-in providers serialize to JSON, and when I tried to store an arbitrary class instance the app threw InvalidOperationException: The 'DefaultTempDataSerializer' cannot serialize an object of type .... If you need a complex object, serialize it to a string yourself or store an ID and look the object up again.

How does TempData compare to ViewData, ViewBag, and Session?

Lifetime Survives a redirect? Typical use
ViewData / ViewBag Current request No Controller to view data
TempData Next request, then removed after it is read Yes Post-redirect-get messages
Session Until the session expires Yes Per-user state across many requests

FAQ

What is TempData in ASP.NET Core? TempData is a per-user dictionary that holds values until they are read on a later request, usually across a redirect. It works in MVC controllers and Razor Pages.

Does the TempData attribute work in Razor Pages? Yes. Decorate a public property on the PageModel (or controller) and ASP.NET Core loads and saves it from TempData. I verified it round-trips across RedirectToPage() and RedirectToAction().

Why is my TempData value null? It was probably already read once, the user did not arrive through the redirect you expected, or you stored a type the serializer cannot handle. Call Keep if you need it to last another request.

Is TempData stored in a cookie or in session? By default, it uses a cookie-based provider. Switch to the session provider with AddSessionStateTempDataProvider() if you prefer to keep data on the server.

Conclusion

TempData is a powerful abstraction that solves many problems. With the [TempData] attribute we can clean up our code from magic strings and potential spelling errors. While not an earth-shattering addition to the stack, we can all agree it’s the little things that matter. For another Razor Pages building block, see handling HTTP status codes with Razor Pages.

Comments

Related Posts