ASP.NET Core State Management: TempData


Imagine a scenario, such as redirecting to another page after registration:

  1. On the registration page: After successful registration, redirect to the login page.
  2. On the login page: Only prompt once for successful registration.

It is usually troublesome to provide operation prompts from the previous page after page redirection, but using TempData makes things simple.

The data in TempData lasts for the next request, and will be deleted at the end of the request, similar to Scoped.

In other words, when assigning a value to a TempData property in the first request, the value can be accessed in the next request, but will be deleted after the request ends. Since TempData is a Dictionary, what gets deleted are key-value pairs.

Its usage is as follows: first, add the [TempData] attribute to the property, indicating that it is temporary data that will be deleted after being read in another request. However, it has multiple usage patterns:

  1. After accessing TempData values, do not delete after the request ends by calling Keep or Peek to keep the data from being deleted.
  2. After accessing TempData values, delete after the request ends by directly accessing the dictionary using TempData["Message"].

For more information, refer to the official documentation:

Complete code reference:

Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.