What is the difference between ViewBag, ViewData and TempData?

ASP.NET MVC Views & Razor Basic Fresher1–2 Yrs2–3 Yrs Conceptual 1 min read

Quick Answer

ViewData is a string-keyed dictionary (ViewDataDictionary) for passing data from a controller to its view, valid for the current request only. ViewBag is a dynamic wrapper over the same dictionary — nicer syntax, no compile-time checking. TempData persists data across one redirect (it is backed by session/cookie), which ViewData/ViewBag cannot do.

ViewData and ViewBag are two ways to reach the same dictionary that carries data from a controller to its view for the current request. ViewData is a string-keyed dictionary so you cast on the way out; ViewBag is a dynamic wrapper so the syntax is cleaner but there's still no compile-time safety. Neither survives a redirect. TempData does — it's backed by session or a cookie, and it keeps a value for exactly one more request, which is why it's used for the “record saved” message in the post-redirect-get pattern. Reading a TempData key consumes it unless you Peek or Keep. For real data I use a strongly typed view model instead of any of them.

ViewDataViewBagTempData
TypeViewDataDictionary (string key)dynamicTempDataDictionary (string key)
Compile-time checkedNo (cast required)NoNo
LifetimeCurrent requestCurrent requestCurrent + next request (survives one redirect)
Backing storeIn-memory per requestSame dictionary as ViewDataSession or cookie provider
Typical usePage title, dropdown listsSame, cleaner syntax“Saved successfully” message after a POST-redirect-GET

Notes:

  • ViewBag.Title and ViewData["Title"] are the same slot.
  • Reading a TempData key marks it for deletion; use TempData.Peek(key) to read without consuming, or TempData.Keep(key) to retain it for another request.
  • For anything non-trivial, prefer a strongly typed view model over all three.

Practise the whole thread the way an interviewer walks it — each question builds on the last.

  1. What is ASP.NET MVC?
  2. Explain the ASP.NET MVC request life cycle.
  3. What is routing in ASP.NET MVC?
  4. What is ActionResult in ASP.NET MVC?
  5. What is the difference between ViewBag, ViewData and TempData?You are here
  6. What is a strongly typed view in ASP.NET MVC?
  7. How does model validation work in ASP.NET MVC?