ASP.NET Core MVC Interview Question #122
What is the difference between Session, TempData, ViewData, and ViewBag?
Authentication, Authorization, Security & State Management Mid-Level Intermediate
Quick Interview Answer
Session persists data across multiple requests for a user until it expires or is removed. TempData is designed for short-lived data that survives a redirect and is typically consumed after it is read.
Detailed Explanation
Session persists data across multiple requests for a user until it expires or is removed. TempData is designed for short-lived data that survives a redirect and is typically consumed after it is read.
ViewData and ViewBag exist only for the current request and pass supplemental information from a controller to a view. Strongly typed ViewModels should normally carry the main data required by a view.
Code Example
ViewData["Title"] = "Checkout";
ViewBag.Message = "Review your order";
TempData["Success"] = "Order placed.";
HttpContext.Session.SetString("CartId", "123");