ASP.NET MVC 3 Preview 1 – Razor Syntax

Posted by: Malcolm Sheridan , on 8/31/2010, in Category ASP.NET MVC
Views: 56805
Abstract: The following article demonstrates how to use the new syntax in the Razor view engine in ASP.NET MVC 3 Preview 1.
Recently I posted an article on the new view engine in ASP.NET MVC 3 Preview 1 - Razor View Engine. The response from that article was good, so I'm continuing on with the new features in the Razor view engine. This article will focus on the Razor syntax. To see this in action, you'll need to download ASP.NET MVC 3 Preview 1 which can be found here. For beta software, I always recommend installing this on a virtual machine, just in case something goes wrong.
Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. Let's get into the Razor syntax. Everything in Razor begins with the @ symbol. So to print out the date and time, do this:
 
The date and time is @DateTime.Now
 
The @ symbol relaces both of the following server syntax:
 
<%: %>
<% %>
 
Immediately you can see the amount of code that is being reduced. One character is replacing many. Everything in the Razor view engine is auto HTML encoded by default, so we could do this safely if we wanted to:
 
@("<script>alert('Hello world!');</script>")
 
This is only for demonstration purposes. Running the script now produces the following result:
 
MVC_3
 
If you wanted the syntax to not be auto HTML encoded, then the easiest way is to wrap it in an MvcHtmlString object. This tells the framework you know what you're doing, so let me control this output of this totally. The above code can be rewritten like this:
 
@MvcHtmlString.Create("<script>alert('Hello world');</script>")
 
The result produces the JavaScript dialog:
 
MVC_1
 
Doing a for loop is simple in Razor, and you'll see there's less typing than in the ASPX view engine:
 
@for(int i = 0;i < 10;i++) {
      <li>@i</li>
}
 
To do the exact same in the ASPX view engine:
 
<% for(int i = 0;i < 10;i++) { %>
      <%: @i %>
<% } %>
 
A lot less code for the same result. Another newbie in the syntax is @View. This gives the view access to the ViewData object, and also the new ViewModel object. ViewModel is a dynamic object that touches the same data dictionary as ViewData, so both of the following lines of code do the same thing:
 
ViewModel.Message = "Welcome to ASP.NET MVC!";
ViewData["Message"] = "Welcome to ASP.NET MVC!";
 
To access the Message value from the view, use the @View object:
 
@View.Message
 
The ViewModel is not limited to simple types such as strings, you can assign collections to it as well:
 
ViewModel.Numbers = Enumerable.Range(0, 10);
 
And to access the numbers use a foreach loop:
 
@foreach(var number in View.Numbers) {
      <li>@number</li>
}
 
But ViewModel doesn't just stop there. You can also use a dynamic object like this:
 
dynamic car = new ExpandoObject();
car.Wheels = 4;
car.Make = "Chevrolet";
car.Model = "Camaro";
ViewModel.Car = car;
 
In the code above I've create a new dynamic object to store info about a car. To access it I can use the following code:
 
The make is @View.Car.Make and the model is @View.Car.Model
 
Nice and simple!
 
One last thing to show you is a new piece of syntax called RenderSection. This gives you the ability to create multiple sections in your layout page, thus allowing it to act like a master page. To create a new section, open the _Layout.cshtml page and do this:
 
@RenderSection("footer")
 
To use that section in the view, add some code to fill it:
 
@section footer {
      <b>Footer here</b>
}
 
But what if I didn't want a section on a particular view? If you removed the above code and ran the site, you'd get this error:
 
MVC_2
 
You're getting that error because the section is mandatory. To make it optional, add a second parameter which is a new .Net 4.0 optional parameter:
 
@RenderSection("footer", optional: true)
 
That's basically it for the Razor syntax. In the next article I'll show you a cool trick to getting the most out of the Razor view engine.
 
The entire source code of this article can be downloaded over here
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Fox on Saturday, September 4, 2010 7:48 AM
Hello dotnetcurry :)

On the for example, the asp.net viewengine is not correct, it should be:

<% for(int i = 0;i < 10;i++) { %>
      <li><%: i %></li>
<% } %>

Really good article, waiting to test asp.net mvc 3, last time tried preview 1, it broke my vs ;(

Comment posted by MickaelDS on Wednesday, April 6, 2011 11:03 AM
Nice post! thanks

http://mickaelds.blogspot.com/
Comment posted by asdas on Tuesday, May 24, 2011 4:28 AM
100% waste tutorial
Comment posted by Jason on Thursday, September 1, 2011 9:55 AM
A quick note about the last part of this article: the "optional: true" must be from an earlier release of Razor. The correct syntax to use these days is "required: false", otherwise you'll get a compilation error.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel