Brendan Enrick's Blog

Daily Software Development.


Difference Between ViewBag and ViewData in MVC 3

by Brendan Enrick Wednesday, August 10 2011 10:00

If you’re new to ASP.NET MVC, you might be wondering what these two things are and when to use each one. If you’ve been using MVC and are just new to version 3 of MVC, you are probably wondering what this new ViewBag is for and if it’s different from the ViewData you’ve been using. In the beginning of the Summer, I had the opportunity to explain this difference to the two NimblePros interns when they started working on ASP.NET MVC 3 for the first time. This post should serve as a reference for them, me, and anyone else who is interested in knowing more about these two objects.

ViewBag and ViewData serve the same purpose in allowing developers to pass data from controllers to views. When you put objects in either one, those objects become accessible in the view. This is one way we interact between the view and the controller in ASP.NET MVC. We pass data from the view to the controller by placing it in these objects.

How ViewData Works

ViewData is a dictionary of objects that are accessible using strings as keys. This means that we will write code like this:

In the Controller

public ActionResult Index()
{
var softwareDevelopers = new List<string>
{
"Brendan Enrick",
"Kevin Kuebler",
"Todd Ropog"
};

ViewData["softwareDevelopers"] = softwareDevelopers;

return View();
}

In the View

<ul>
@foreach (var developer in (List<string>)ViewData["softwareDevelopers"])
{
<li>
@developer
</li>
}
</ul>

Notice that when we go to use out object on the view that we have to cast it since the ViewData is storing everything as object. Also, we need to be careful since we’re using magic strings to access these values.

How ViewBag Works

ViewBag uses the dynamic feature that was added in to C# 4. It allows an object to dynamically have properties added to it. The code we write using ViewBag will look like this:

In the Controller

public ActionResult Index()
{
var softwareDevelopers = new List<string>
{
"Brendan Enrick",
"Kevin Kuebler",
"Todd Ropog"
};

ViewBag.softwareDevelopers = softwareDevelopers;

return View();
}

In the View

<ul>
@foreach (var developer in ViewBag.softwareDevelopers)
{
<li>
@developer
</li>
}
</ul>

Notice here that we did not have to cast our object when using the ViewBag. This is because the dynamic we used lets us know the type. Keep in mind that these dynamics are as the name suggest, dynamic, which means that you need to be careful as these are basically magic properties instead of magic strings.

ViewBag and ViewData Under the Hood

So these two things seem to work almost exactly the same. What’s the difference? The difference is only in how you access the data. ViewBag is actually just a wrapper around the ViewData object, and its whole purpose is to let you use dynamics to access the data instead of using magic strings. Some people prefer one style over the other. You can pick whichever you like. In fact, because they’re the same data just with two different ways of accessing it, you can use them interchangeably. (I don’t recommend this, but you can do it.) If you want you are able to put data into the ViewBag and access it from the ViewData or put stuff in the ViewData and access it in the ViewBag.

This is all that the ViewBag property is. It’s just a DynamicViewDataDictionary with the ViewData as its data.

public dynamic ViewBag 
{
get
{
if (_dynamicViewData == null)
{
_dynamicViewData =
new DynamicViewDataDictionary(() => ViewData);
}
return _dynamicViewData;
}
}

Then when we access the dynamic members of the DynamicViewDataDictionary, we are actually just getting this override of the DynamicObject’s TryGetMember. In this method, it’s just using the name of the member we tried to access as the string key for the ViewData dictionary.
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
result = ViewData[binder.Name];
return true;
}

So for a short answer:

These two objects are two different ways of accessing the exact same data. The ViewBag is just a dynamic wrapper around the ViewData dictionary.

Tagged as: ,

Comments

9/3/2011 8:06:21 AM #

Parsa

Well,
Nice! But How about the direction of carrying the data? I mean, Does ViewBag (or ViewData) pick up the data in the client side and give it to server or vice versa? And might both?

thax

Parsa Iran

9/7/2011 4:19:27 PM #

Brendan Enrick

Parsa,

As ASP.NET (Web Forms or MVC) is primarily a server-side framework, it does not pass the data between client and server.

In Web Forms is was common for ViewState to do this kind of transfer between client and server, but neither ViewData nor ViewBag do that. Both are used for transferring data before that point. It is the data used from these that are rendered into the HTML.

I hope that answers your questions.

Thanks,
Brendan

Brendan Enrick United States

9/7/2011 11:46:32 PM #

Parsa

Thanks,
So as I understood, both of Viewbag and Viewdata, are for transfering data between the components in the server side. The one which is sent to client is the rendered Html, after using those data in the scripts.

Regards,
Parsa

Parsa Iran

10/28/2011 4:56:09 PM #

pingback

Pingback from programmersgoodies.com

Html.ActionLink() call error - Programmers Goodies

programmersgoodies.com

11/24/2011 12:02:31 AM #

trackback

Difference Between ViewBag and ViewData in MVC 3

Thank you for submitting this cool story - Trackback from Blue Ray Plus - Latest Technology News

Blue Ray Plus - Latest Technology News

12/16/2011 5:32:26 AM #

trackback

Difference between ViewBag and ViewData

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com

1/4/2012 2:29:14 PM #

Brian

Very nice, clear and concise explanation. I am new to MVC and really new to asp .net. It is kind of difficult to find basic explanations. Thanks again.  

Brian United States

1/15/2012 10:33:13 AM #

AJ

Nice Article, It will use for Mvc Beginners. Thanks a lot.

AJ India

2/2/2012 4:32:32 AM #

peter

Thanks mate.

peter United States

2/3/2012 1:30:15 AM #

Mahesh

Very nice explanation.. Thank You..

Mahesh India

2/9/2012 1:25:18 PM #

Elfrieda

I just couldn’t depart your website prior to suggesting that I extremely enjoyed the standard info a person provide for your visitors? Is gonna be back often in order to check up on new posts

Elfrieda United States

2/10/2012 3:25:04 AM #

Bhuvin

Thanks ! Awesomely explained !

Bhuvin India

4/18/2012 8:04:15 AM #

shebin

Thanks.....very nice and awesome explanation

shebin India

5/12/2012 6:28:47 AM #

Pankaj

Thanks. As I'm new to MVC. This difference cleared one of my question..

Pankaj India

5/23/2012 7:31:21 PM #

pingback

Pingback from dkphp.com

How are the View's @Model, ViewDataDictionary, ViewData and ViewBag related with each other? | PHP Developer Resource

dkphp.com

7/23/2012 8:13:04 PM #

Nikos

cool, but how come you lose the data if you redirect to a view after setting the data

Nikos United States

7/25/2012 4:50:46 PM #

Brendan Enrick

Hi Nikos,

That's a good question.

Basically, this type of data storage is very temporary. It's for passing from your controller to the view being displayed by your controller's action. What that means, is that the content rendering happening immediately after the controller action is the last point where that data survives, so as soon as you send data back to the browser the data is no longer being stored.

I assume, based on your saying that you "redirect to a view", that you're returning a "RedirectToAction" result in your action. That will return an HTTP 302 response to the browser, which will cause the browser to make an entirely new request to the new action. The data we stored was during the previous request to the server.

Please let me know if that answers your question.

Brendan Enrick United States

8/9/2012 6:07:54 AM #

Vikram Rawal

Nice post for understanding difference on it.

ThanksSmile

Vikram Rawal India

11/7/2012 9:47:06 AM #

pingback

Pingback from singleconcept.wordpress.com

What is the Difference Between ViewBag and ViewData in MVC 3? | singleconcept

singleconcept.wordpress.com

2/21/2013 4:32:44 AM #

pingback

Pingback from dotnetblogdiscussion.wordpress.com

Difference Between ViewBag and ViewData in MVC 3 « Dot Net Blogs Discussion

dotnetblogdiscussion.wordpress.com

7/2/2013 10:58:49 PM #

pingback

Pingback from hirendhara.biz

How to get viewbag data in Asp.net MVC? | Q Sites

hirendhara.biz

Comments are closed