In ASP.NET Core MVC or Razor Pages, when does a TempData value survive into the next request, and how do Keep and Peek change that?
answer
- reading marks a key for deletion
- unread values carry over
- Peek(key) reads without marking
- Keep(key) or Keep() retain read values
- redirect results call Keep() for you
basics
~20 sTempData keeps a value until a request reads it; at the end of that request read keys are removed and unread keys are saved again. Peek(key) reads without marking, Keep(key) or Keep() retains read values, and redirect results call Keep() automatically.
solid answer
~40 s`TempData` (on `Controller`, `PageModel` and through `[TempData]` properties) is a dictionary that is loaded from its provider on first use and saved by the `SaveTempDataFilter` before the response starts. Reading a key through the indexer, `TryGetValue` or enumeration **marks it for deletion**; when the request ends, marked keys are dropped and everything unread is written back, so a value lives until some request reads it. `Peek("Saved")` returns the value without marking it, `Keep("Saved")` un-marks one read key, and `Keep()` retains every key. Results that implement `IKeepTempDataResult` (`RedirectResult`, `RedirectToActionResult`, `RedirectToRouteResult`, `RedirectToPageResult`) call `Keep()` before saving, so a read followed by a redirect does not consume the value. Values are limited to simple types such as `string`, `int`, `bool`, `DateTime`, `Guid` and enums.
code
csharp · 12 linespublic class ApplicationModel : PageModel
{
[TempData]
public string? Saved { get; set; }
public IActionResult OnPost(PreApprovalForm form)
{
// ... persist the application ...
Saved = "Pre-approval saved";
return RedirectToPage("Summary"); // RedirectToPageResult keeps TempData
}
}go deeper
Explain TempData as the place for a one-time message after a redirect, and that reading it normally removes it.
Walk through mark-on-read and save-at-end, then contrast Peek, Keep(key) and Keep(), and mention that redirect results call Keep() automatically.
Diagnose stale banners from unread keys, serializer failures on complex types, and values lost on intermediate pages, and choose between Peek and Keep accordingly.
Keep TempData to small, disposable UI messages; anything a business flow depends on belongs in durable storage, not in a best-effort dictionary.
## What TempData is for **TempData** is the MVC and Razor Pages dictionary for data that must survive **exactly until the next request reads it**. The classic use is the one-time confirmation after a form post and redirect: a mortgage pre-approval page saves an application, sets `TempData["Saved"] = "Pre-approval saved"`, redirects, and the next page shows the banner once. It is available as `Controller.TempData`, `PageModel.TempData`, through properties marked `[TempData]`, and from `ITempDataDictionaryFactory.GetTempData(HttpContext)` elsewhere. `ControllerBase`, the base class for API controllers, has no `TempData` property, and Minimal APIs have no TempData at all. ## The life cycle of one request 1. **Load.** `TempDataDictionary` is lazy: the first access calls `ITempDataProvider.LoadTempData` and remembers every loaded key as a candidate to keep. 2. **Read.** The indexer, `TryGetValue` and enumeration remove the key from that candidate set: the value is now **marked for deletion**. `ContainsKey` and `Peek` do not mark. 3. **Write.** Setting `TempData["Saved"]` adds the key as a candidate to keep. 4. **Save.** `SaveTempDataFilter` calls `Save()` when the result has executed, or from a `Response.OnStarting` callback. Keys that were read and not retained are removed; the rest are passed to the provider. The consequence surprises people in both directions: - A value that **nobody reads** is saved again and again, so a banner set on one page can appear several requests later on whichever page first renders it. - A value read on an intermediate page is **gone** for the page after it, unless that page called `Peek`, called `Keep`, or returned a redirect. ## Keep and Peek | Call | Effect on the value at the end of the request | |---|---| | `TempData["Saved"]` | returned and marked for deletion | | `TempData.Peek("Saved")` | returned, not marked, so it survives | | `TempData.Keep("Saved")` | a previously read key is retained | | `TempData.Keep()` | every loaded key is retained | | `TempData.Remove("Saved")` | removed immediately | `Peek` is the right tool when a layout wants to inspect a value that a later page should still display. `Keep` fits when the code has already read through the indexer and decides afterwards that the value must stay. ## Redirects keep everything `SaveTempDataFilter` checks whether the action result implements `IKeepTempDataResult`. `RedirectResult`, `RedirectToActionResult`, `RedirectToRouteResult` and `RedirectToPageResult` do, and for them the filter calls `Keep()` before `Save()`. An action that reads `TempData["Saved"]` and then returns `RedirectToAction("Index")` therefore does not consume the message; the page it redirects to still sees it. Note that `Keep()` with no arguments does nothing if TempData was never loaded in the request. ## What can be stored The default `TempDataSerializer` writes JSON and accepts only: - `string`, `int`, `bool`, `DateTime`, `Guid` and enums (and their nullable forms); - `ICollection<int>`, `ICollection<string>` and `IDictionary<string, string>`. Storing anything else, for example a `PreApprovalSummary` object, throws `InvalidOperationException` (*cannot serialize an object of type*) when TempData is saved. Serialize the object to a JSON string yourself, or store an identifier and reload the data. Keys are compared case-insensitively. ## Where it is stored By default `CookieTempDataProvider` keeps the dictionary in an encrypted cookie; `AddSessionStateTempDataProvider()` moves it into session state. The choice changes where the bytes live, not the read-marks-for-deletion rules above.
- In ASP.NET Core MVC, why does a TempData message sometimes appear on a page several requests after it was set?Only reads mark a key for deletion. If the page reached after the redirect never reads `TempData["Saved"]`, perhaps because the view checks a different key or the user navigated elsewhere, the value is saved again at the end of each request. It stays until the first page that reads it, which may be much later. Read it where it is meant to be shown, or `Remove` it explicitly.
- In ASP.NET Core MVC, does checking TempData.ContainsKey("Saved") consume the value?No. `ContainsKey` loads the dictionary but does not remove the key from the set of values to keep, so the value survives the request. The indexer, `TryGetValue` and enumeration are the reads that mark a key for deletion; `Peek` is the explicit non-consuming read.
TempData is a note left at a hotel front desk: it waits until the guest collects it and is thrown away once collected, unless the guest only glances at it through the window (Peek) or asks the desk to hold it (Keep), which the desk also does by itself when it sends the guest on to another counter (a redirect).
- TempData is deleted after the next request whether or not it is read
- Peek removes the value just like the indexer does
- Any serializable object can be stored in TempData directly
- Reading TempData and then redirecting always loses the value
- API controllers deriving from ControllerBase can use TempData