myesn

myEsn2E9

hi
github

ASP.NET Core State Management: TempData

Introduction#

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: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state#tempdata

Complete code reference: https://github.com/myesn/temp-data-in-asp-dotnet-core

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