Controller in ASP.NET MVC 2 (MVC 3 also) supports property named ViewData. ViewData help us to pass data from controllers to views , in between views using using a late-bound dictionary API. ViewData is property of type ViewDataDictionary in ControllerBase class. ViewData properties are stored as name/value pairs in the ViewData dictionary.
Lets understand it by example, Here is HomeController, Index action method is using ViewData property to set a message & Index.cshtml View is same ViewData property to render values on web page.
ASP.NET MVC 3 introduces a new property named ViewBag which is dynamic property in ControllerBase class. As we know ASP.NET MVC 3 built on top of .NET Framework 4, so it uses full power of C# 4.0, dynamic properties is a new feature in C# 4.o, you can read more about dynamic properties at : http://msdn.microsoft.com/en-us/library/dd264736.aspx
As ViewBag is a dynamic property, instead of writing ViewData[“Message”]=”text”, we can write ViewBag.Message=”text”, We can just get or set properties and it will resolve them dynamically at run time.ViewBag internally uses ViewData to store the values, ViewBag properties are stored as name/value pairs in the ViewData dictionary. So we can use ViewData in controller , ViewBag in View & vice versa.
To prove ViewBag internally uses ViewData, Lets use ViewBag in Controller , Use ViewData in View with same key name, even though output would be same.
Again output is same, we can use these ViewData/ViewBag to pass values between views also. Important thing about this properties is we should use the to pass simple data like, simple strings or collection key values pairs to bind to a dropdown or any other control in view, we should not use them pass huge data.If you need to work with larger amounts of data we should use Models/ViewModels.