Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 RC - Razor "View" Property

Just mucking around with Razor in the ASP.NET MVC 3 RC released today.

Now, we have a concept of a "Layout Page", which i presume is the replacement of the "View Master" in the ASPX view engine.

But i do not understand the "View" property of the layout page.

Here is the example which is created when you create a new Razor View:

_Layout.cshtml

<html>
<head>
   <title>@View.Title</title>

...

MyView.cshtml

@model Mvc3FunParty.Models.Post

@{
   View.Title = "Some Title";
   Layout = "~/Views/Shared/_Layout.cshtml";
}

Which results in "Some Title" being inserted into the <title> tag of the rendered HTML.

How on earth does this work? When i hover over the "View" property, it's of type "dynamic".

So what exactly should this property be used for? Can we stuff anything in there? Is this supposed to be the Razor implementation of ViewData?

And if so, shouldn't it be of type "ViewDataDictionary"? Why the "dynamic" type for the View property?

like image 528
RPM1984 Avatar asked Nov 10 '10 05:11

RPM1984


1 Answers

The View property is an alias for the ViewData property. That means that the following code

View.Title

is equivalent to

ViewData["Title"]

This works by using the new 'dynamic' feature of the C# language introduced in .NET 4. Basically it allows you to write late-bound code in what has until now been a statically-typed language. There's plenty of resources on the web if you want to learn more.

The ViewData property is still available and you can use both interchangaebly. They both use the same backing storage so changes made one way will be available the other way.

The advantage of using View is more concise syntax. The disadvantage is that you do not get IntelliSense support.

The reason why you can set View.Title in your view page and the correct value shows up in the layout page is due to the rendering order of Razor pages. We call it the inside-out rendering, which means that your view page gets executed first, it's HTML output gets collected into a buffer, then the layout page gets executed, and the buffered view page output gets injected where you call RenderBody.

like image 176
marcind Avatar answered Sep 28 '22 02:09

marcind