What is the difference between ViewBag, ViewData and TempData?
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.
| ViewData | ViewBag | TempData | |
|---|---|---|---|
| Type | ViewDataDictionary (string key) | dynamic | TempDataDictionary (string key) |
| Compile-time checked | No (cast required) | No | No |
| Lifetime | Current request | Current request | Current + next request (survives one redirect) |
| Backing store | In-memory per request | Same dictionary as ViewData | Session or cookie provider |
| Typical use | Page title, dropdown lists | Same, cleaner syntax | “Saved successfully” message after a POST-redirect-GET |
Notes:
ViewBag.TitleandViewData["Title"]are the same slot.- Reading a
TempDatakey marks it for deletion; useTempData.Peek(key)to read without consuming, orTempData.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.
- What is ASP.NET MVC?
- Explain the ASP.NET MVC request life cycle.
- What is routing in ASP.NET MVC?
- What is ActionResult in ASP.NET MVC?
- What is the difference between ViewBag, ViewData and TempData?You are here
- What is a strongly typed view in ASP.NET MVC?
- How does model validation work in ASP.NET MVC?