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

# ViewBag dynamic in ASP.NET MVC 3 - RC 2 - Hajan's Blog

Saturday, December 11, 2010 4:13 PM by ViewBag dynamic in ASP.NET MVC 3 - RC 2 - Hajan's Blog

Pingback from  ViewBag dynamic in ASP.NET MVC 3 - RC 2 - Hajan's Blog

# ViewBag dynamic во ASP.NET MVC 3 - RC 2

Saturday, December 11, 2010 4:55 PM by Hajan's Blog - MKDOT.NET

Како што пишав во претходниот блог денес Scott Guthrie го најави ASP.NET MVC 3 - Release Candidate 2

# Dew Drop &ndash; December 11, 2010 | Alvin Ashcraft&#039;s Morning Dew

Saturday, December 11, 2010 8:19 PM by Dew Drop – December 11, 2010 | Alvin Ashcraft's Morning Dew

Pingback from  Dew Drop &ndash; December 11, 2010 | Alvin Ashcraft&#039;s Morning Dew

# Twitter Trackbacks for ViewBag dynamic in ASP.NET MVC 3 - RC 2 - Hajan's Blog [asp.net] on Topsy.com

Pingback from  Twitter Trackbacks for                 ViewBag dynamic in ASP.NET MVC 3 - RC 2 - Hajan's Blog         [asp.net]        on Topsy.com

# The Morning Brew - Chris Alcock &raquo; The Morning Brew #749

Monday, December 13, 2010 3:39 AM by The Morning Brew - Chris Alcock » The Morning Brew #749

Pingback from  The Morning Brew - Chris Alcock  &raquo; The Morning Brew #749

# Sortie d’ASP.Net MVC 3

Tuesday, December 14, 2010 3:38 PM by This blog is dead, long live this blog

Il y a quelques jours est sortie la version finale d’ASP.Net MVC 3, cette troisième, et toujours plus

# 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 04, 2011 5:21 PM by hajan

@Ignacio, nice suggestion. Thank you.

# Dynamic V Strongly Typed Views

Friday, January 28, 2011 6:49 PM by Ricka on MVC & Dynamic Data

There are three ways to pass information from a controller to a view in ASP.NET MVC 3: As a strongly

# ASP.NET MVC: Don&rsquo;t Fear the ViewBag &laquo; Affirma Consulting Blog

Pingback from  ASP.NET MVC:  Don&rsquo;t Fear the ViewBag &laquo; Affirma Consulting Blog

# ASP.NET MVC 3 Fundamentals &laquo; 2nd Step

Wednesday, February 16, 2011 5:25 PM by ASP.NET MVC 3 Fundamentals « 2nd Step

Pingback from  ASP.NET MVC 3 Fundamentals &laquo; 2nd Step

# MVC ViewBag

Thursday, February 17, 2011 4:38 PM by Biztalk Musings

MVC ViewBag

# Biztalk Musings | MVC ViewBag

Thursday, February 17, 2011 4:38 PM by Biztalk Musings | MVC ViewBag

Pingback from  Biztalk Musings | MVC ViewBag

# MVC 3 | JimFrenette.com

Tuesday, April 26, 2011 7:21 AM by MVC 3 | JimFrenette.com

Pingback from  MVC 3 | JimFrenette.com

# MVC 3 Razor : Creating Custom HTML Helpers &laquo; ASP.NET MVC Code Samples

Pingback from  MVC 3 Razor : Creating Custom HTML Helpers &laquo; ASP.NET MVC Code Samples

# re: ViewBag dynamic in ASP.NET MVC 3

Tuesday, July 26, 2011 8:55 AM by Ganga

Thank you

# Asp.net MVC3 ViewBag of dynamic

Thursday, October 06, 2011 12:13 PM by Asp.net MVC3 ViewBag of dynamic

Pingback from  Asp.net MVC3 ViewBag of dynamic

# Using Microsoft POS for .NET in 2011

Tuesday, November 08, 2011 8:41 AM by LavaBlast Software Blog

Using Microsoft POS for .NET in 2011

# ASP.NET MVC3: Applying a SELECT / WHERE Statement from MVC View - Programmers Goodies

Pingback from  ASP.NET MVC3: Applying a SELECT / WHERE Statement from MVC View - Programmers Goodies

# ASP.NET MVC3: Applying a SELECT / WHERE Statement from MVC View - Programmers Goodies

Pingback from  ASP.NET MVC3: Applying a SELECT / WHERE Statement from MVC View - Programmers Goodies

# 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?

# Web Programming by 1cainr - Pearltrees

Monday, December 12, 2011 3:20 PM by Web Programming by 1cainr - Pearltrees

Pingback from  Web Programming by 1cainr - Pearltrees

# 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

Sunday, December 18, 2011 7:21 AM by hajan

@Bob, is it ASP.NET MVC3? If yes, please check this post stackoverflow.com/.../mvc-3-the-name-viewbag-does-not-exist-in-the-current-context - it might help you...

# 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 04, 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)

# ViewBag vs ViewData in ASP.NET MVC | Monir&#039;s Blog

Tuesday, July 10, 2012 3:04 PM by ViewBag vs ViewData in ASP.NET MVC | Monir's Blog

Pingback from  ViewBag vs ViewData in ASP.NET MVC | Monir&#039;s Blog

# 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?

Leave a Comment

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