In ASP.NET MVC and ASP.NET Core MVC, there are four ways to pass data from the controller to view and in the next request: ViewData, ViewBag, TempData, and Session. However, they have different scopes and lifetimes. Each of them has its importance. In this article, I will try to explain the differences among these.
ViewDatais a dictionary-like object available in both ASP.NET MVC and ASP.NET Core MVC.
- It’s a dictionary of objects that is derived from
- It is used to communicate between the controller and the view.
- It is not type-safe and requires casting in the view.
- It persists data during a single request. Once the request is processed, the data is no longer available.
- It’s commonly used when strongly typed models are not preferred.
ViewBagis a dynamic property that is used
- It’s a wrapper around
ViewDatato provide a dynamic property-like syntax for adding data.
- It’s also not type-safe and requires casting in the view.
- It persists data during a single request, just like
- It’s commonly used when passing data to a view without creating a custom view model.
TempDatais a dictionary-like object available in both ASP.NET MVC and ASP.NET Core MVC.
- It’s used to pass data between controller actions or between redirects.
- It persists data for the duration of an HTTP request (including redirects). After reading, the data is marked for deletion and will not be available in subsequent requests.
- It’s useful for scenarios like passing errors or status messages between actions or during redirection.
- It’s type-safe in ASP.NET Core MVC, as it uses the
TempDataDictionaryclass, but not type-safe in ASP.NET MVC.
- In ASP.NET MVC, Session is a property of the Controller class whose type is HttpSessionStateBase.
- The session is also used to pass data within the ASP.NET MVC application. Unlike TempData, it persists for its expiration time (by default, the session expiration time is 20 minutes but can be increased).
- The session is valid for all requests, not for a single redirect.
- It also required typecasting for getting data and checking for null values to avoid errors.
Choosing the right option
- For simple data sharing within a single request: Use
ViewDatafor strong typing or
- For temporary data between consecutive requests: Use
- For long-term user-specific data: Use
Sessioncautiously, considering performance and security implications.
ViewBagare used to pass data from the controller to view during a single request.
TempDatais used to pass data between actions or redirects for a short duration (across requests).
In this article, I tried to explain the difference between ViewData, ViewBag, TempData, and Session. I hope you will refer to this article for your needs. I would like to have feedback from my blog readers. Please post your feedback, questions, or comments about this article.