DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

Tempdata vs View Bag vs ViewData

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.
  2. 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.
  3. 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.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay