ViewData in MVC3 Razor

1. ViewData serve the same purpose as ViewBag 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. ViewData is a dictionary of objects that are accessible using strings as keys.

Watch Video

Following is the way we use ViewData :

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 ViewData.
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 ViewData in many ways.
3. In above snapshot we accessed the ViewData 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.

Rendered View :

Points To Remember :

1. ViewData stores everthing as object. So we have to type cast it to the type used while assigning object to ViewData.
2. Be careful while using the string key. Key plays important part in accessing the ViewData's content.
3. ViewData is used to pass values from controller to the View, but you cannot use it the other way i.e from View to Controller.


Post a Comment