Difference between ViewBag, ViewData, TempData in ASP.NET MVC

ASP.NET MVC provide ViewData, ViewBag and TempData for maintaining the data between controller to view, controller to action, action to action.

Similarities between ViewBag & ViewData :

ViewBag & ViewData are used to maintain data while travelling from controller to view.

This communication is only for server call, it becomes null if redirect occurs.

It’s life span is short because the data will became null when redirection occurs. The main pupose of viewData and ViewBag is to maintain the data while travelling from controller to view.

ViewData

ViewData is a dictionary object. It is derived from viewDataDictionary class.

Typecasting is required for complex data type and need to checks for null values to avoid error

ViewBag

ViewBag is a dynamic property (The properties that are associated with the dynamic are ignored at the compile time).

It doesn’t require typecasting.

TempData

TempData is derived from TempDataDictionary class

Tempdata helps to store/preserve values within in a single request. TempData preserve values for the next request based on 4 different conditions in MVC. More about temp data click here (It helps to maintain the data when we move from one controller to another controller or from one action to another action).

It requires typecasting for complex data type and checks for null values to avoid error.