ASP.NET MVC 3: ViewBag Property

In the previous versions of ASP.NET MVC, if you wanted to pass data from your controller to your view you had to use the ViewData dictionary:

public ActionResult Index()
{
            ViewData[“DataComingFromTheController”] =
                            “I’m data coming from the controller”;
            return View();
}

In your view:

<%: ViewData[“DataComingFromTheController”]  %>

Because ASP.NET MVC 3 is .NET 4, Microsoft could take benefit of the dynamic keyword to create dynamic properties. So instead of using the ViewData dictionary, you can use the ViewBag property, which makes coding easier:

public ActionResult Index()
{
         ViewBag.DataComingFromTheController
                = “I’m data coming from the controller”;
         return View();
}

and in your view:

@ViewBag.DataComingFromTheController

When we take a closer look on the ViewBag property, we’ll see that it’s a dynamic property (also notice that ViewData still exists):

image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: