ViewBag dynamic in ASP.NET MVC 3

Earlier today Scott Guthrie announced the ASP.NET MVC 3 - Release Candidate 2. I installed the new version right after the announcement since I was eager to see the new features. Among other cool features included in this release candidate, there is a new ViewBag dynamic which can be used to pass data from Controllers to Views same as you use ViewData[] dictionary. What is great and nice about ViewBag (despite the name) is that its a dynamic type which means you can dynamically get/set values and add any number of additional fields without need of strongly-typed classes.

In order to see the difference, please take a look at the following examples.

Example - Using ViewData

Controller

public ActionResult Index()
{
    List<string> colors = new List<string>();
    colors.Add("red");
    colors.Add("green");
    colors.Add("blue");            

    ViewData["listColors"] = colors;
    ViewData["dateNow"] = DateTime.Now;
    ViewData["name"] = "Hajan";
    ViewData["age"] = 25;

    return View();
}


View (ASPX View Engine)

<p>
    My name is
    <b><%: ViewData["name"] %></b>,
    <b><%: ViewData["age"] %></b> years old.
    <br />    
    I like the following colors:
</p>
<ul id="colors">
<% foreach (var color in ViewData["listColors"] as List<string>){ %>
    <li>
        <
font color="<%: color %>"><%: color %></font>
    </
li>
<% } %>
</ul>
<p>
    <%: ViewData["dateNow"] %>
</p>

(I know the code might look cleaner with Razor View engine, but it doesn’t matter right? ;) )


Example - Using ViewBag

Controller

public ActionResult Index()
{
    List<string> colors = new List<string>();
    colors.Add("red");
    colors.Add("green");
    colors.Add("blue");

    ViewBag.ListColors = colors; //colors is List
    ViewBag.DateNow = DateTime.Now;
    ViewBag.Name = "Hajan";
    ViewBag.Age = 25;
    return View();
}

You see the difference?

View (ASPX View Engine)

<p>
    My name is
    <b><%: ViewBag.Name %></b>,
    <b><%: ViewBag.Age %></b> years old.
    <br />    
    I like the following colors:
</p>
<ul id="colors">

<% foreach (var color in ViewBag.ListColors) { %>
    <li>
        <font color="<%: color %>"><%: color %></font>
    </li>
<% } %>

</ul>
<p>
    <%: ViewBag.DateNow %>
</p>

In my example now I don’t need to cast ViewBag.ListColors as List<string> since ViewBag is dynamic type! On the other hand the ViewData[“key”] is object.

I would like to note that if you use ViewData["ListColors"] = colors; in your Controller, you can retrieve it in the View by using ViewBag.ListColors.

And the result in both cases is

Hope you like it!

Regards,
Hajan

Published Saturday, December 11, 2010 10:10 PM by hajan
Filed under: , ,

Comments

# re: ViewBag dynamic in ASP.NET MVC 3 - RC 2

Saturday, December 18, 2010 1:53 PM by Nikolaj

I dont understand why you guys fancy dynamic objects so much!

All the help you get from the compiler is disabled and runtime errors / bugs will occur more likely than if the property has been on a "normal" object and typos would be catched by the compiler.

In my opinion I would rather use the ViewData[] dictionary. This at least signals to the "bug" finder that there could be a typo in play.

# re: ViewBag dynamic in ASP.NET MVC 3 - RC 2

Sunday, December 19, 2010 7:56 AM by hajan

@Nikolaj, I partially agree with you. I mean, that is the disadvantage of using dynamic objects, however, there are many other advantages. That's why you have to choice either to use this or that way. At least, one advantage of using dynamic object is shown in my blog post ;). Thank you for your feedback.

# re: ViewBag dynamic in ASP.NET MVC 3 - RC 2

Monday, December 27, 2010 8:42 PM by Ignacio

I much prefer to write expansion methods to ViewDataDictionary to manage my necessities, for example:

<Extension>

Function ListColors(vdd As ViewDataDictionary(Of T)) As List(Of String)

 Return DirectCast(ViewData("listColors"), List(Of String))

End Function

With this little effort you can use ViewData.ListColors, just the same as ViewBag.ListColors but with Intellisense and strong types!

# re: ViewBag dynamic in ASP.NET MVC 3 - RC 2

Tuesday, January 4, 2011 5:21 PM by hajan

@Ignacio, nice suggestion. Thank you.

# re: ViewBag dynamic in ASP.NET MVC 3

Monday, November 28, 2011 5:16 PM by Bob Spencer

I have problem with my project, I get this error

Error 1 The name 'ViewBag' does not exist in the current context

What can I do?

# re: ViewBag dynamic in ASP.NET MVC 3

Tuesday, December 13, 2011 5:10 PM by Bob Elander

The name 'ViewBag' does not exist in the current context.  I am getting this error what can I do??

# re: ViewBag dynamic in ASP.NET MVC 3

Friday, December 30, 2011 4:24 AM by Chhaya

Nice Example....Thanks.

# re: ViewBag dynamic in ASP.NET MVC 3

Wednesday, January 11, 2012 1:56 AM by faraz

gr8 for mvc3 beginners.....

# re: ViewBag dynamic in ASP.NET MVC 3

Sunday, March 4, 2012 11:41 PM by rajdeep paliwal

i found nice definition of ViewBag...thanks a lot

# re: ViewBag dynamic in ASP.NET MVC 3

Monday, March 26, 2012 7:06 PM by Eric

Wonderful post. I learned many interesting things. Thank you)

# re: ViewBag dynamic in ASP.NET MVC 3

Thursday, November 29, 2012 2:13 AM by Raju

Very Good Article..!

# re: ViewBag dynamic in ASP.NET MVC 3

Sunday, March 17, 2013 6:20 PM by alireza

hi

I can not use "viewbag",however namespace System.Web.Mvc.dll was added in my project,this error will be appear"unknown type of member "view bag""

can you help me?

# re: ViewBag dynamic in ASP.NET MVC 3

Friday, August 2, 2013 4:52 AM by sridhar

Very nice explanation for beginners.

Leave a Comment

(required) 
(required) 
(optional)
(required)