Difference Between ViewData, ViewBag and TempData

Introduction

In Asp.Net MVC there are three ways to pass/store data between the controllers and views.

ViewData

  1. ViewData is used to pass data from the controller to the view.
  2. It is derived from the ViewDataDictionary class.
  3. It is available for the current request only.
  4. Requires typecasting for complex data type and checks for null values to avoid error.
  5. If redirection occurs, then its value becomes null.

ViewBag

  1. ViewBag is also used to pass data from the controller to the respective view.
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  3. It is also available for the current request only.
  4. If redirection occurs, then its value becomes null.
  5. Doesn’t require typecasting for complex data types.

TempData

  1. TempData is derived from the TempDataDictionary class.
  2. TempData is used to pass data from the current request to the next request.
  3. It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action.
  4. It requires typecasting for complex data types and checks for null values to avoid errors. Generally, it is used to store only one-time messages like error messages and validation messages.