Skip to main content

What is ViewData, ViewBag, and TempData?

Junior .NET Core
Quick Answer ViewData: dictionary, requires casting when reading, ViewData["Title"] = "Home". ViewBag: dynamic wrapper over ViewData รขโ‚ฌโ€ ViewBag.Title = "Home". TempData: survives a redirect รขโ‚ฌโ€ stored in cookie or session. All three pass data from controller to view within a request. ViewData and ViewBag are equivalent; TempData is the only one that persists across redirects.

Answer

  • ViewData โ€“ A Dictionary<string, object> for passing data from controller to view in the same request.
  • ViewBag โ€“ A dynamic wrapper around ViewData for more convenient syntax.
  • TempData โ€“ Persists data across one redirect; cleared after it is read.

ViewData/ViewBag are for same-request communication; TempData is designed for redirect scenarios such as Post-Redirect-Get.

S
SugharaIQ Editorial Team Verified Answer

This answer has been peer-reviewed by industry experts holding senior engineering roles to ensure technical accuracy and relevance for modern interview standards.

Want to bookmark, take notes, or join discussions?

Sign in to access all features and personalize your learning experience.

Sign In Create Account

Source: SugharaIQ

Ready to level up? Start Practice