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 communicaton between controller and View. Both have short life that is the value of both becomes null once the redirection has occured 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.
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";
and can access as follows:
@ViewBag.Name
While in case of ViewData the values can be set and accessed as follows: Setting ViewData as follows :
ViewData["Name"] = "Value";
and accessing value like this
@ViewData["Name"]
For more details click here: