Wednesday, February 9, 2011

ASP.NET MVC3 Razor Notes - view data

The WebViewPage in an abstract class that inherits from the WebViewPage<TModel> generic abstract class.

Two properties of the WebViewPage<TModel> generic abstract class are:

  1. Model (dynamic)
  2. ViewData (key/value collection)

Among other properties, the WebViewPage adds:

  1. ViewBag (dynamic)

The ViewBag property is another way to get to the ViewData data.

For example:

If in the controller you did the following:

ViewData["website"] = "guyellisrocks.com";
ViewData["somenumbers"] = Enumerable.Range(0, 10);

Then in the view you could access that data through the ViewBag:

<div>
    @ViewBag.website
</div>
@foreach (int i in ViewBag.somenumbers)
{
<div>
    @i
</div>
}

and this would emit to the web page:

guyellisrocks.com
0
1
2
3
4
5
6
7
8
9
 

No comments:

Post a Comment