Sunday, December 8, 2013

ViewData ViewBag and TempData in MVC

ViewData is a 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.
ViewData["Name"] = "Hello World !";
string strValue = ViewData["Name"].ToString();

ViewBag is data structure has been created to utilize C# 4.0 possibility of having dynamic Variables.  This 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.
ViewBag.Name = "Hello World !"
strint strValue = ViewBag.Name;

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 It requires typecasting for complex data type and check for null values to avoid error.
TempData["Name"] = "Hello World !"
string strValue = TempData["Name"] != null ? TempData["Name"].ToString() : String.Empty;

The important difference between ViewData-ViewBag  and  TempData  is the life time of the structure.

There is also the possibility to use Session. It is he 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 dataIt requires typecasting for complex data type and check for null values to avoid error.
Session["Name"] = "Hello World !";
string strValue = Session["Name"] != null ? Session["Name"].ToString() : String.Empty ;

Regarding ViewData or ViewBag you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular asp.net mvc request. You can use ViewData/ViewBag in your child action but be careful that you are not using it to populate the unrelated data which can pollute your controller.

No comments:

Post a Comment