ViewBag and ViewData in MVC

This article explains the two view objects used to pass data from a controller to a view.

Both ViewBag and ViewData are used to pass data from a controller to a view. Let's look at both of them one by one.

ViewBag

ViewBag uses the dynamic feature to add a property on the go that was introduced in C# 4.0.

DEMO

Create a new ASP.NET MVC project and select the project template as empty and view engine as Razor.

Click OK.

empty tamplet

It will create an empty project for us.

Go to the Solution Explorer, right-click on the Controllers folder then select Add -> Controller.

controller

Provide the controller name as HomeController and select the Empty MVC controller template.

homecontroller

Click Add.

Our HomeController is now created.

controllr.cs

So, let's write some code inside the Index action method.

dynamic expression

When we say ViewBag(.), an intellisense pops up that states it is a dynamic expression that resolves at runtime.

In this ViewBag we can pass any dynamic data that we want and this data acts as a dynamic property.

We will add BrandName as the dynamic data.

code

We have created a new list object in which we have added five string values and we have assigned the data to the ViewBag.BrandName and in the end we are retuning the view.

Save and run the application.

errors

We get an exception because we are returning a view back but we haven't created it yet and since it is an Index action method we will be creating a view with the same name, Index.
 
But before proceeding let's first see what actually this View function returns.

viewresult controller

The return type of the view function is a ViewResult but our Index action method returns an ActionResult back. So, why are we not getting an error?

Go to the definition of the view function by pressing F12 or by right-clicking on the view function and select go to definition.

First you will see that the View function returns ViewResult back.

protected

If you go to the definition of ViewResult you will see this class inherits from the ViewResultBase class.

protected view

And now if you go to the definition of this ViewResultBase class, you will see this class inherits from the ActionResult class.

code

This is the reason, we can use the return type as ActionResult even if the view function returns ViewResult back.

Let's add an Index view.

razor.cshtml

Click Add.

Our Index.cshtml file will be created inside the Views folder.

index.cs

Inside the div tag, we will create an un-ordered list.
  1. <ul>  
  2.   
  3. </ul>  
The next step is to loop through each BrandName and for that we need to use a foreach loop.

code foreach

In the Razor view engine, if you want to switch from HTML to C# code then use "@".

We will loop through each string items present in the ViewBag.BrandName dynamic property.
 

code

Currently we have all the data in the item that we retrieved from the ViewBag.BrandName property.

The next step is to add and display these items in a form of a list and for that we can use <li> </li>.

linrea list

Run the application.

local host

We have successfully passed the data from a controller to a view using ViewBag.DynamicData.

Let's see how to do the same thing using ViewData.

ViewData is a dictionary of objects that are stored and retrieved using a string as keys.

string key

Pass the key as “BrandName”.

viewedata

We have passed the indexed string key in the ViewData in which we are storing the new list object.

In the Index view, we need to make some changes. Now we need to loop through each ViewData[“BrandName”].

for loop
Save and run the application.

When we run our application, we get a compilation error because we haven't type-casted the ViewData into an appropriate type. Currently the ViewData returns a ViewdataDictionary object back.

server error

As we know this ViewData is storing the data of type List<string>. So, in order to retrieve those string values we need to type-caste it to a List<string>.

foreach loop

Run the application.

sony
We have now seen both of the ways to pass data from a controller to a view.

But there is a drawback in both of them.

Both ViewData and ViewBag do not provide a compile-time error check. So, if we misspell the keys or property name, we won't get a compile time error. We get the error only at runtime.

Here I am changing BrandName to BrandNames.



If we build this application, we will not get an error but when we run the application, we will get an error.

server error

For this reason, it is a good practice to create strongly-typed views as we discussed in the previous article of the MVC series. To learn more click here and scroll down to the Views section.

Thank you.

Up Next
    Ebook Download
    View all
    Learn
    View all