In this lesson, you will learn how to maintain user data across multiple HTTP requests using TempData and Session state.
Why State Matters
Because HTTP is a stateless protocol, the server forgets everything about a user as soon as a request finishes. While ViewData or model-passing techniques are great for rendering a single page, they cannot carry information from one navigation action to the next. When you need to pass data through a redirect—like a success message after a form submission—you need a way to persist that state.
Using TempData for One-Time Messages
TempData is designed for short-lived data that is intended to be read exactly once. It is perfect for "Flash" messages. When you set a value in TempData, it is stored in the session until it is read, at which point it is immediately marked for deletion.
// Inside your Razor Page handler
public IActionResult OnPost()
{
// Logic to save data...
TempData["Message"] = "Profile updated successfully!";
return RedirectToPage("Index");
}
On your destination page, you can simply access it:
@TempData["Message"]
Using Session for Long-Term Context
If you need to persist data for the duration of a user’s entire browsing session (like a shopping cart or a multi-step wizard), Session is the correct tool. Unlike TempData, session data persists until the session expires or is manually cleared.
To use Session, you must first ensure it is enabled in your Program.cs via builder.Services.AddSession(). You can then store complex objects by serializing them to JSON:
HttpContext.Session.SetString("UserPreferences", JsonConvert.SerializeObject(prefs));
Choosing the Right Tool
- TempData: Best for redirect scenarios and one-off notifications. It is backed by session state but handles the cleanup for you.
- Session: Best for keeping state across multiple pages during a user's visit. Remember that session storage consumes server memory, so avoid storing large objects or sensitive information that doesn't need to be tracked long-term.
Key Takeaway: Use TempData for transitory messages that disappear after one read, and Session for data that must persist throughout the user's ongoing interaction with your application.