ViewData: A Dictionary for the Current Request
ViewData is a ViewDataDictionary exposed on both the controller and the view, used to pass supplementary data alongside the strongly typed model, such as ViewData["PageTitle"] = "Products". Because it's keyed by string and typed as object, reading a value back requires an explicit cast, like (string)ViewData["PageTitle"], and a typo in the key string produces a silent null at runtime rather than a compile error, which is why it's best reserved for small, secondary pieces of view metadata rather than core page data.
Cricket analogy: Like a scorer jotting extra notes on a scorecard margin, such as 'pitch report: dry, expect turn', ViewData holds supplementary information alongside the main scorecard (the model) rather than being the primary record itself.
ViewBag: Dynamic Access Over the Same Dictionary
ViewBag is a dynamic wrapper over the exact same underlying ViewDataDictionary as ViewData, so ViewBag.PageTitle and ViewData["PageTitle"] read and write the identical value, just with different syntax; ViewBag.PageTitle = "Products" uses C# dynamic typing to avoid the string-indexer and cast that ViewData requires. Because ViewBag relies on the DLR (Dynamic Language Runtime), a misspelled property name like ViewBag.PagTitle compiles fine but silently returns null at runtime, so neither ViewBag nor ViewData catches typos at compile time the way a strongly typed model does.
Cricket analogy: Like two different scoreboards, a digital one and a manual flip-card one, both showing the same underlying score, ViewBag and ViewData are two syntaxes reading and writing the same underlying dictionary.
// In the controller action
public ActionResult Index()
{
ViewData["PageTitle"] = "Product Catalog";
ViewBag.LastUpdated = DateTime.UtcNow;
var products = _repository.GetAll();
return View(products);
}
// In Index.cshtml
<h1>@ViewBag.PageTitle</h1>
<p>Last updated: @ViewData["LastUpdated"]</p>TempData: Surviving a Single Redirect
TempData is designed for the Post-Redirect-Get pattern: a value set in one action, such as TempData["SuccessMessage"] = "Order placed!", survives exactly one subsequent request, typically the redirect target after a successful form POST, because ASP.NET MVC's default TempDataProvider stores it in session state and marks it for deletion once read. Calling TempData.Keep("SuccessMessage") preserves a value for one additional request if you need it to survive further than the default single hop, and TempData.Peek("SuccessMessage") reads the value without marking it for removal at all.
Cricket analogy: Like a 'target score' displayed only during the chase innings and cleared once that innings ends, TempData holds a value for exactly the next request (the redirect target) and is cleared after being read.
The Post-Redirect-Get pattern uses TempData to carry a success or error message from the POST action, after RedirectToAction("Index"), into the GET action that renders the result page — this avoids the classic 'confirm form resubmission' browser warning caused by returning a View() directly from a POST.
TempData's default provider relies on session state, so it will not work correctly if sessions are disabled, and it should not be used to store large objects or as a general-purpose cache — it's meant strictly as a short-lived, single-hop message carrier between a redirect and the request that follows it.
When to Use Each One
Use TempData exclusively for values that must survive a redirect, like a one-time status message after Post-Redirect-Get. Use ViewData or ViewBag interchangeably for small pieces of view-only metadata within the current request that don't belong on the strongly typed model, such as a dynamically computed page title or a dropdown's SelectList; ViewBag is generally preferred for readability since ViewBag.Title reads more cleanly than ViewData["Title"]. For anything that represents the actual page data, always prefer a strongly typed view model over any of these three, since only the model gets IntelliSense and compile-time checking.
Cricket analogy: Like choosing between a permanent scoreboard entry (the model), a scribbled margin note for this innings only (ViewBag/ViewData), and a message relayed only to the very next over (TempData), each mechanism fits a different lifespan of data.
- ViewData is a string-keyed ViewDataDictionary requiring explicit casts; typos in keys fail silently at runtime.
- ViewBag is a dynamic wrapper over the identical dictionary as ViewData — same data, different (property) syntax.
- TempData persists a value for exactly one subsequent request, designed for the Post-Redirect-Get pattern.
- TempData.Keep() extends a value's life by one more request; TempData.Peek() reads without marking for deletion.
- TempData's default provider relies on session state, so it doesn't work with sessions disabled.
- Prefer a strongly typed view model for core page data; reserve ViewBag/ViewData/TempData for small, secondary metadata.
Practice what you learned
1. What is the underlying relationship between ViewBag and ViewData?
2. How many subsequent requests does a TempData value survive by default?
3. What does TempData.Keep("key") do?
4. Why is a strongly typed view model generally preferred over ViewBag or ViewData for core page data?
5. What must be true for the default TempDataProvider to work correctly?
Was this page helpful?
You May Also Like
Strongly Typed Views
Learn how the @model directive binds a Razor view to a specific C# class, enabling IntelliSense, compile-time checking, and clean use of lambda-based helpers.
The Razor View Engine
Understand how Razor compiles .cshtml templates into C# classes, its @ syntax, encoding rules, and how it fits into the ASP.NET MVC request pipeline.
HTML Helpers
Learn how HtmlHelper extension methods generate form controls, links, and validation markup in Razor views, and how they differ from raw HTML.
Related Reading
Related Study Notes in Microsoft Technologies
Browse all study notesWindows 10 / UWP Development Study Notes
.NET · 30 topics
Microsoft TechnologiesWindows Batch Scripting Study Notes
Batch · 30 topics
Microsoft TechnologiesMFC (Microsoft Foundation Classes) Study Notes
C++ · 30 topics
Microsoft TechnologiesSilverlight Study Notes
.NET · 30 topics
Microsoft TechnologiesXAML Study Notes
.NET · 30 topics
Microsoft TechnologiesWPF (Windows Presentation Foundation) Study Notes
.NET · 30 topics