Saturday, January 29, 2011

MVC 3 – Razor Syntax Introduction

 

Razor has been one of the most anticipated additions to the third release of MVC. So far, for me, it has made it very easy to quickly shape views.

So, a brief description of Razor would be … ?

A way to use a new markup (NOT the same old <% [code here] %> server code escape syntax) but something new, cleaner, and a bit more intuitive, IMHO.

Razor was first made available in the WebMatrix tools, so you may have seen it here.

How does one use this in an MVC project?

To use it, one must have installed the MVC 3 framework, as it is included as part of this.  When you create a project, open up a view from the initial pages created, you will notice it has the ‘@’ –symbol peppered throughout. This is what Razor uses as an escape sequence.

The first thing you should know, since you probably are already familiar with the <%…%> notation, is that you are still able to place code-blocks into your view. With Razor it is done like this:

@{
View.Title = "MVC3 Test Page";
LayoutPage = "~/Views/Shared/_Layout.cshtml";
}

This code just sets the title of the current view and the LayoutPage’s location [which is equivalent to a MasterPage].


By the same token, one may also introduce server-side properties with similar notation, such as:

This page was created by @View.Name and Copyright @View.CopyrightYear. Please contact @View.AdminEmail for more information.




The above line really exposes the clean nature of Razor’s ‘@’ syntax.


One may also use this syntax to write multiline comments:

@*  This is a comment
that spans multiple
lines.
*@



Easy enough. You can also include code in here, and the rendering engine will ensure that these are comments, and are rendered as text but not executed.

@*
var i = 99;
for(var count = 199; count >= i; count--)
{
//found an easier way, using foreach
// see below.
}
*@




Of course, the above would be rendered as a comment in HTML and not executed.


One may build tables with Razor just as easy, but if you are doing too much work with a table that displays a subset of data, one may want to use the new WebGrid, which I plan to cover soon.

<table>
@foreach(var item in listOfItems){
<tr>
<td>@item.Name</td><td>@item.Value</td>
</tr>
}
</table>


While, for, and other loops are treated no differently than this. One may also use decision statements similarly, such as if/else if/else and switch statements.


In summary, I’ve given a brief introduction to Razor, why it is much preferred to the older escape notation (<%…%>) and how to use it in certain situations to add code to HTML pages.


The next time I will get into some of the major additions that Razor brings along, such as the Html extension methods and reusing HTML helpers.


Wes

No comments:

Post a Comment