ViewBag and ViewData are two means which are used to pass information from controller to view in ASP.Net MVC. The goal of using both mechanism is to provide the communication between controller and View. Both have short life that is the value of both becomes null once the redirection has occurred ie, once the page has redirected from the source page (where we set the value of ViewBag or ViewData) to the target page , both ViewBag as well as ViewData becomes null.

See ALSO : Difference between Var , dynamic and Object in C#

Despite having these similarities both (ViewBag and ViewData) are two different things if we talk about the implementation of both. The differences are as follows :

1.) If we analyse both implementation wise then we will find that ViewData is a dictionary data structure - Dictionary of Objects derived from ViewDataDictionary and accessible using strings as Keys to these values while ViewBag makes use of the dynamic features introduced in C#4.0 and is a dynamic property.

2.) While accessing the values form ViewData , we need to typecast the values (datatypes) as they are stored as Objects in the ViewData dictionary but there is no such need if we are accessing th value in case of ViewBag.

3.) In ViewBag we can set the value like this :
ViewBag.Name = "Value"; 

The value can be accessed as follows:

While in case of ViewData the values can be set and accessed as follows:
Setting ViewData : ViewData["Name"] = "Value";
Accessing value   :   @ViewData["Name"]

The differences can be summed up as follows:

It is Key-Value Dictionary collection
It is a type object
ViewData is a dictionary object and it is property of ControllerBase class
ViewBag is Dynamic property of ControllerBase class.
ViewData is Faster than ViewBag
ViewBag is slower than ViewData
ViewData is introduced in MVC 1.0 and available in MVC 1.0 and above
ViewBag is introduced in MVC 3.0 and available in MVC 3.0 and above
ViewData  is also work with .net framework 3.5 and above
ViewBag  is only  work with .net framework 4.0 and above
Type Conversion code is required while enumerating
In depth, ViewBag is used dynamic, so there is no need to type conversion while enumerating.
It value become null if redirection is occurred.
Same as ViewData
It lies only during the current request.
Same as ViewData


Post a Comment