ViewBag dynamic in ASP.NET MVC 3 - RC 2

Posted by hajan on ASP.net Weblogs See other posts from ASP.net Weblogs or by hajan
Published on Sat, 11 Dec 2010 21:10:00 GMT Indexed on 2010/12/12 6:22 UTC
Read the original article Hit count: 741

Filed under:
|
|

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

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about ASP.NET MVC