9.6 — ViewData vs ViewBag vs TempData¶
← Roadmap · Section: 9. MVC, Razor Pages and Views Prev: 9.5 Partials, view components and tag helpers · Next: 9.7 Razor Pages
Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Three untyped bags for passing data around, and the difference that matters is how long each one lives.
ViewData— a dictionary. Lives for one request, controller to view.ViewBag— the same dictionary, accessed withdynamicsyntax. Identical storage.TempData— survives one redirect. Backed by session or cookies. For flash messages.
⚠️ All three are untyped, so a typo gives you null rather than a compile error. Use a ViewModel for real data.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
ViewData |
a ViewDataDictionary |
String-keyed dictionary of object. One request. |
ViewBag |
a dynamic wrapper |
The same storage as ViewData, with property syntax. |
TempData |
an ITempDataDictionary |
Survives one redirect. Read-once semantics. |
| Read-once | TempData's behaviour | Reading a value marks it for deletion at the end of the request. |
Peek |
a method | Reads a TempData value without marking it read. |
Keep |
a method | Marks a value to survive another request after reading. |
[TempData] |
an attribute | Binds a property to TempData, giving a typed-ish accessor. |
| Cookie TempData provider | the default | Stores TempData in an encrypted cookie. |
| Session TempData provider | the alternative | Stores it server-side. Requires session. |
| PRG | Post-Redirect-Get | The pattern TempData exists to support. |
| ViewModel | a typed class | What you should use instead for real data. See 9.8. |
The concept¶
ViewData and ViewBag are the same thing¶
This is the part people get wrong. They are two syntaxes over one dictionary:
ViewBag is a dynamic wrapper around ViewData. Nothing is stored separately.
The difference is only in how mistakes surface:
ViewData["Titel"] // returns null — a typo in a string
ViewBag.Titel // returns null — a typo in a property name, resolved at runtime
Neither gives you a compile error. ViewBag looks more type-safe and is not — dynamic
resolution happens at runtime, so a misspelled property is just null.
⚠️ ViewBag has one extra hazard: casting. Because it is dynamic, arithmetic and comparisons
can fail at runtime in surprising ways:
ViewData["Count"] = 5;
var doubled = ViewBag.Count * 2; // works — dynamic resolves int
var text = ViewBag.Count.ToUpper(); // compiles, throws at runtime
Prefer ViewData. The string key is at least visibly a lookup, and ViewBag's property syntax
gives a false impression of safety.
What TempData is for¶
ViewData dies at the end of the request. After a redirect, it is gone:
[HttpPost]
public IActionResult Create(CreateOrderRequest request)
{
var order = _orders.Create(request);
ViewData["Message"] = "Order created"; // ⚠️ lost on redirect
return RedirectToAction(nameof(Details), new { id = order.Id });
}
A redirect is a new request, so the dictionary is fresh and empty.
TempData survives exactly one redirect:
TempData["Success"] = "Order created"; // ✓ available after the redirect
return RedirectToAction(nameof(Details), new { id = order.Id });
A picture: a note passed hand to hand. ViewData is shouting across the room — heard now,
gone immediately. TempData is a note that survives being carried to the next room, and is
destroyed once read.
Why the redirect exists at all¶
TempData is really a supporting cast member for Post-Redirect-Get.
Without a redirect, a successful POST returns HTML directly. Then the user presses refresh, the browser re-submits the POST, and the order is created twice. The browser even warns about it — "Confirm Form Resubmission" — which users ignore.
PRG fixes it: POST → redirect → GET. After the redirect the browser's current URL is a GET, so
refreshing is harmless. TempData is how the success message survives that redirect.
How it works¶
The simple version¶
// ── ViewData: this request only ──
public IActionResult Details(Guid id)
{
ViewData["Title"] = "Order details";
ViewData["ShowBackLink"] = true;
return View(model);
}
@* Reading it — casting is required, because everything is object *@
<h1>@ViewData["Title"]</h1>
@if (ViewData["ShowBackLink"] is true)
{
<a asp-action="Index">Back</a>
}
⚠️ Everything comes back as object, so numbers and booleans need casting or pattern
matching. @if (ViewData["ShowBackLink"]) does not compile.
// ── TempData: survives one redirect ──
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CreateOrderRequest request, CancellationToken ct)
{
if (!ModelState.IsValid) return View(request);
var order = await _orders.CreateAsync(request, ct);
TempData["Success"] = $"Order {order.Reference} created.";
return RedirectToAction(nameof(Details), new { id = order.Id });
}
@* Usually in the layout, so every page can show it — see 9.4 *@
@if (TempData["Success"] is string success)
{
<div class="alert alert-success">@success</div>
}
⚠️ TempData is read-once¶
Reading a value marks it for deletion:
var message = TempData["Success"]; // read — now marked for removal
var again = TempData["Success"]; // still available in THIS request
// but gone in the next one
That is usually what you want — a flash message should appear once. But it causes a real bug:
@* ⚠️ Reading it in the layout consumes it *@
@if (TempData["Message"] is string m) { <div>@m</div> }
@* ...then a view tries to read it too, and it is gone next request *@
Two methods control this:
TempData.Peek("Success"); // read WITHOUT marking it read
TempData.Keep("Success"); // after reading, keep it for one more request
TempData.Keep(); // keep everything
Peek is the one to remember, and the fix when a value disappears earlier than expected.
The [TempData] attribute¶
A slightly safer accessor:
public class OrdersController : Controller
{
[TempData]
public string? SuccessMessage { get; set; }
[HttpPost]
public IActionResult Create(...)
{
SuccessMessage = "Order created"; // written to TempData
return RedirectToAction(nameof(Details));
}
}
@* Still untyped in the view, unless it is on the ViewModel *@
@if (TempData["SuccessMessage"] is string m) { <div>@m</div> }
⚠️ The property must be public and settable, and only string and simple types work reliably —
complex objects require serialization and the cookie provider will not handle them well.
How it actually works — where TempData is stored¶
Two providers, and the difference matters in production.
Cookie provider (the default):
The value is serialised, encrypted with the Data Protection API and sent as a cookie.
⚠️ Three consequences. It adds to every request's headers until consumed. Cookies have a ~4 KB limit, so a large object silently fails. And it depends on Data Protection keys being shared across servers — otherwise a request hitting a different instance cannot decrypt it (17.6).
Session provider:
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();
builder.Services.AddControllersWithViews()
.AddSessionStateTempDataProvider();
app.UseSession(); // before UseEndpoints
Stored server-side, so no size limit and nothing on the wire.
⚠️ But it makes your application stateful. With more than one instance you need a distributed cache such as Redis, or requests hitting a different server find nothing (24.12).
The cookie provider is the better default for a scaled-out application, provided you share Data Protection keys and keep values small.
The deeper detail — when to use none of them¶
⚠️ For real data, use a ViewModel.
// ✗ Untyped, no IntelliSense, typos are silent
ViewData["CustomerName"] = order.Customer.Name;
ViewData["OrderTotal"] = order.Total;
ViewData["CanCancel"] = order.CanBeCancelled(now);
// ✓ Typed, discoverable, refactorable, testable
return View(new OrderDetailsViewModel
{
CustomerName = order.Customer.Name,
Total = order.Total,
CanCancel = order.CanBeCancelled(now)
});
The legitimate uses are narrow:
| Use | Which |
|---|---|
| Page title for the layout | ViewData["Title"] |
| Flash message across a redirect | TempData |
| Something a layout needs that no ViewModel would carry | ViewData |
| Anything else | A ViewModel (9.8) |
ViewData["Title"] is the canonical acceptable case, because the layout needs it and adding a
Title property to every ViewModel would be worse.
⚠️ And none of these exist on ControllerBase. They are Controller members, so an API
controller does not have them — which is correct, since an API has no views
(9.2).
Code¶
The full Post-Redirect-Get pattern:
[Route("orders")]
public class OrdersController(IOrderService orders) : Controller
{
[HttpGet("create")]
public IActionResult Create()
{
ViewData["Title"] = "New order";
return View(new CreateOrderViewModel());
}
[HttpPost("create")]
[ValidateAntiForgeryToken] // see 17.4
public async Task<IActionResult> Create(CreateOrderViewModel model, CancellationToken ct)
{
if (!ModelState.IsValid)
{
ViewData["Title"] = "New order";
return View(model); // redisplay — no redirect, no TempData
}
var result = await orders.CreateAsync(model.ToRequest(), ct);
if (!result.IsSuccess)
{
ModelState.AddModelError(string.Empty, result.Error);
ViewData["Title"] = "New order";
return View(model);
}
// POST → REDIRECT → GET, so a refresh does not re-submit
TempData["Success"] = $"Order {result.Value.Reference} was created.";
return RedirectToAction(nameof(Details), new { id = result.Value.Id });
}
[HttpGet("{id:guid}")]
public async Task<IActionResult> Details(Guid id, CancellationToken ct)
{
var order = await orders.GetAsync(id, ct);
if (order is null) return NotFound();
ViewData["Title"] = $"Order {order.Reference}";
return View(OrderDetailsViewModel.From(order)); // real data on the ViewModel
}
}
@* Views/Shared/_Layout.cshtml — flash messages in one place *@
<main>
@if (TempData["Success"] is string success)
{
<div class="alert alert-success" role="alert">@success</div>
}
@if (TempData["Error"] is string error)
{
<div class="alert alert-danger" role="alert">@error</div>
}
@RenderBody()
</main>
Three things to notice.
On a validation failure the action returns View(model), not a redirect — because ModelState
does not survive a redirect either, so redirecting would lose the error messages
(11.5).
TempData only appears on the success path, where there is a redirect for it to survive.
Real data goes on the ViewModel; only the title and the flash message use the untyped bags.
Interview questions¶
Q: What is the difference between ViewData and ViewBag?
None, in terms of storage — ViewBag is a dynamic wrapper around the same ViewData dictionary,
so setting ViewBag.Title and reading ViewData["Title"] gives you the same value. The only
difference is syntax: a string key versus a property. Neither is type-safe; a misspelled property
on ViewBag resolves at runtime to null just as a misspelled string key does. I prefer ViewData
because the string key is visibly a dictionary lookup, whereas ViewBag's property syntax gives a
false impression of compile-time safety.
Q: What is TempData for, and how does it work?
It carries data across a redirect, which ViewData cannot do because a redirect is a new request.
The main use is a flash message in the Post-Redirect-Get pattern — you POST, redirect so a refresh
does not re-submit the form, and the success message survives to be shown on the GET. It is
read-once: reading a value marks it for deletion at the end of the request, which is usually what
you want for a one-time message. Peek reads without consuming, and Keep preserves a value for
another request.
Q: Where is TempData stored?
By default in a cookie, serialised and encrypted with the Data Protection API. That means it travels on every request until consumed, is limited to roughly four kilobytes, and requires Data Protection keys to be shared across instances — otherwise a request hitting a different server cannot decrypt it. The alternative is the session provider, which keeps it server-side with no size limit, but that makes the application stateful and needs a distributed cache like Redis once you scale out. For a scaled-out app the cookie provider is usually the better default, with shared keys and small values.
Q: When should you use these rather than a ViewModel?
Rarely. For real data a ViewModel is better in every way — typed, discoverable, refactorable, and
the compiler catches mistakes. The legitimate cases are narrow: ViewData["Title"] for the layout,
because adding a Title property to every ViewModel would be worse, and TempData for a flash
message across a redirect. Anything the page actually renders should be on the ViewModel.
Traps ⚠️¶
ViewBagis not type-safe. A misspelled property resolves to null at runtime, silently.- Everything comes back as
object.@if (ViewData["Flag"])does not compile — pattern match or cast. ViewDatadoes not survive a redirect. UseTempData.TempDatais read-once, so reading it in a layout consumes it. UsePeekif something else needs it.- Cookie TempData is limited to ~4 KB and fails silently above that.
- Cookie TempData needs shared Data Protection keys across instances, or it cannot be decrypted.
- Session TempData makes the app stateful, breaking scale-out without a distributed cache.
ModelStatedoes not survive a redirect either — redisplay the view on validation failure.- None of these exist on
ControllerBase. API controllers do not have them.
Related¶
- 9.8 ViewModels — what to use instead for real data
- 9.2 Controllers — why
ControllerBaselacks these - 9.4 Razor and layouts —
ViewData["Title"]in the layout - 11.5 ModelState — why validation failures redisplay
- 17.4 CSRF — the antiforgery token on the POST
- 17.6 Data Protection — why cookie TempData breaks in a farm
- 24.12 Scaling — why session state is a problem