Tempdata vs View Bag vs ViewData

Sardar Mudassar Ali Khan
1 min readJan 12, 2024

In ASP.NET MVC, TempData, ViewBag, and ViewData are used to pass data between controllers and views, but they serve different purposes and have different lifetimes.

  1. ViewData:
  • ViewData is a dictionary that is used to pass data from the controller to the corresponding view.
  • It is valid only during the current request.
  • Once the view is rendered, ViewData is no longer available.
  1. ViewBag:
  • ViewBag is a dynamic property that is a wrapper around ViewData.
  • Like ViewData, it is valid only during the current request.
  • It is useful when you want to pass data from the controller to the view without strongly typing it.
  1. TempData:
  • TempData is also a dictionary, but its data persists for an additional request.
  • It is useful when you want to transfer data from the current request to the next request (e.g., after a redirect).
  • TempData is typically used for scenarios where you need to pass data between actions or controllers during a redirect.

If you need to store data for a longer duration or make it persistent, you should consider other options like session variables, caching, or storing in a database. Keep in mind that TempData is not meant for permanent storage and should be used for short-term data transfer between requests.

--

--

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Written by Sardar Mudassar Ali Khan

8x-Microsoft Certified Senior Software Engineer | MCT|MCT |Microsoft Certified Cloud Solution Architect | Microsoft Certified Cloud Developer | Technical Author