ViewData and ViewBag
We saw how Models and ViewModels can be used to pass data from controller to the view. But now consider scenario where we need to pass small amount of data from controllers to view. Now for every such case if we start creating ViewModels then managing these view models will become a nightmare. For all such requirements where we need to transfer small amount of data, we can use Viewdata and ViewBag.
ViewData
ViewData is an in built dictionary object that can be accessed and set with string type key values. It is derived from ViewDataDictionary class and is a very handy data structure when it comes to passing data from Controller to View. The data is only alive for one request and cannot persist between request. The only problem with ViewData is that the type casting is required for complex data types at the location where the data is being extracted.
ViewBag
C# 4.0 has the possibility of having dynamic Variables. ViewBag data structure has been created to utilize this and is written as a wrapper over the ViewData so that the type casting for complex objects will not be required if we use ViewBag. ViewBag comes with all the benefits of ViewData with an additional benefit that type casting is not required.
TempData
Now the problem with all the above ways of data transfer was that the data is only alive for current request. The data is lost if a redirection takes place i.e. one Action redirects to another action. For the scenarios where we need to persist the data between actions/redirection another dictionary object called
TempData
can be used. It is derived from TempDataDictionary. It is created on top of session. Its will live till the redirected view is fully loaded.
Sessions
Session is the way to persist the data till the current session is alive. If we need some data to be accessible from multiple controllers, actions and views then Session is the way to store and retrieve the data.