1. ViewBag serve the same purpose as ViewData in allowing developers to pass data from controllers to views.
2. When you put objects in either one, those objects become accessible in the view.
3. This is one way we interact between the view and the controller in ASP.NET MVC3.
4. We pass data from the view to the controller by placing it in these objects.
5. ViewBag is actually just a wrapper around the ViewData object, and its whole purpose is to let you use dynamics to access the data.
6. ViewBag uses the dynamic feature that was added in to C# 4. It allows an object to dynamically have properties added to it.
Following is the way we use ViewBag :
In Controller :
1. When you add a new controller, you will get an default action method named Index(). You can change that or keep it same.
2. Create a Generic List of type string as shown in the snapshot.
3. Add string value to the list.
4. Assign the list object to the ViewBag.
5. That is all you need to do in the controller. Lets see what to do in the View.
In View :
1. Add a view by right clicking inside the action method. View name should be same as the action method.
2. Inside the view you can iterate through the ViewBag in many ways.
3. In above snapshot we accessed the ViewBag by string key(same we used in controller), iterated the ViewData in the foreach loop.
4. Finally rendered the values inside h3 tag one by one.
Points To Remember :
1. ViewBag is just a DynamicViewDataDictionary with the ViewData as its data. So you dont need to typecast the ViewBag as you do in ViewData.
2. Be careful while using the string key. Key plays important part in accessing the ViewData's content.
3. ViewBag is used to pass values from controller to the View, but you cannot use it the other way i.e from View to Controller.
4. The ViewBag is just a dynamic wrapper around the ViewData dictionary.