ASP.NET Core MVC Beginner

TempData

TempData holds a value until it is read, which makes it ideal for showing a message after a redirect, such as "Your order was saved". This lesson shows how TempData works, how long values live, and the Keep and Peek methods.

A TempData message across a redirect
  1. StartPOST action savesTempData["Message"] = "Order saved"
  2. Step 2Redirect is returnedThe value is stored, in a cookie by default
  3. Step 3Browser follows itA new GET request arrives
  4. Step 4Next view reads it@TempData["Message"] shows the text
  5. EndValue is removedOnce read, it is deleted at the end of the request

The idea in plain words

After a successful form POST you redirect (Post-Redirect-Get), and the redirect starts a brand-new request. ViewData and ViewBag are gone by then. TempData bridges that gap: you write a value in one request and read it in a later one, and it is removed automatically after it has been read.

By default ASP.NET Core keeps TempData in a protected cookie, so it works without session. Keep the values small and simple, such as strings, numbers and booleans.

Example

The controller sets a message and redirects; the layout shows it on whatever page comes next.

C#
public class OrdersController : Controller
{
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(OrderModel model)
    {
        if (!ModelState.IsValid) return View(model);
        await _orders.AddAsync(model);
        TempData["Message"] = "Your order was saved.";
        return RedirectToAction(nameof(Index));
    }
}

Showing it, and keeping it longer

Reading a value marks it for deletion. Peek reads without marking it, and Keep keeps values for one more request.

Razor
@* Views/Shared/_Layout.cshtml *@
@if (TempData["Message"] is string message)
{
    <div class="alert">@message</div>
}

@* In C#: read without removing, or keep everything for one more request *@
@{
    var draft = TempData.Peek("Draft");
    TempData.Keep();
}

Common mistakes

  • Storing complex objects directly. Serialize them to a JSON string first, or store just an id.
  • Expecting TempData to survive several requests after it has been read.
  • Putting large data in TempData; it is sent back and forth in a cookie.

Interview question

What is the difference between ViewData, ViewBag and TempData?

ViewData and ViewBag pass data from a controller to a view within the same request and are gone afterwards; ViewBag is a dynamic wrapper over ViewData. TempData persists across requests until it is read, which makes it suitable for passing a message across a redirect. TempData uses a cookie-based provider by default and can be kept with Keep or read without removal with Peek.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.