Brendan Enrick

Daily Software Development

Difference Between ViewBag and ViewData in MVC 3

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.

Comments (14) -

  • Parsa

    9/3/2011 8:06:21 AM | Reply

    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

  • Brendan Enrick

    9/7/2011 4:19:27 PM | Reply

    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

  • Parsa

    9/7/2011 11:46:32 PM | Reply

    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

  • Brian

    1/4/2012 2:29:14 PM | Reply

    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.  

  • AJ

    1/15/2012 10:33:13 AM | Reply

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

  • peter

    2/2/2012 4:32:32 AM | Reply

    Thanks mate.

  • Mahesh

    2/3/2012 1:30:15 AM | Reply

    Very nice explanation.. Thank You..

  • Elfrieda

    2/9/2012 1:25:18 PM | Reply

    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

  • Bhuvin

    2/10/2012 3:25:04 AM | Reply

    Thanks ! Awesomely explained !

  • shebin

    4/18/2012 8:04:15 AM | Reply

    Thanks.....very nice and awesome explanation

  • Pankaj

    5/12/2012 6:28:47 AM | Reply

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

  • Nikos

    7/23/2012 8:13:04 PM | Reply

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

  • Brendan Enrick

    7/25/2012 4:50:46 PM | Reply

    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.

  • Vikram Rawal

    8/9/2012 6:07:54 AM | Reply

    Nice post for understanding difference on it.

    ThanksSmile

Loading