Getting Familiar with Razor Language Syntax, Features and Rules

All languages have syntax rules, and ASP.NET Web Pages with Razor is no different.  The syntax is meant to be light and concise and simple, yet powerful enough to allow you to move to ASP.NET development using Visual Studio easily . Having said that, let’s take a look at a few key features of the language and some of the simple ways to write Razor code.

What exactly IS Razor and WebMatrix?

If you need the introduction on WebMatrix & Razor, no worries, I’ve already written a post on why, who and when WebMatrix & Razor are good choices and what they are intended for here.  Otherwise, continue on…

Basic Principles (Code/Script Blocks)

The @ character designates inline code, which is code that’s right inside of HTML  while the @{ with and ending } designates multiple lines of code.  Inline code can be anywhere – mixed inline with HTML, as HTML attribute values or page content. It can be multiple lines of code (a code block) as well when more functionality is needed.  Here’s a single inline statement sample with the actual code highlighted:

<li class=”price”>$@string.Format(“{0:f}”, p.Price)</li>

And here’s a what a block of code looks like:

@{

    LayoutPage = “~/_Layout.cshtml”;

    PageData[“Title”] = “Home”;

}

 

Each executable statement ends with a semicolon (;).Whitespace is ignored, but case is not.

Literal strings (or literal text) are put in double quotations (“), while numbers, if used mathematically, use none.

Comments

A Razor single line comment marker: @//

A Razor multi-line comment marker: @/* and */

Variables & Data Types

Use the var keyword to declare variables, or use the classic typed syntax.  The new operator is also supported.

var db = Database.Open(“bakery”);

string name = “Stephen”

int rating = 5;

var grid = new WebGrid(data, defaultSort: “Na
me”, rowsPerPage: 5);

Razor supports all the standard .NET framework simple data types and allows developers to take advantage of consuming objects and collections, using the classic dot notation, as shown below:

Mail.SmtpServer = “smtp.live.com”;

Mail.SmtpPort = 25;

Mail.EnableSsl = true;

Mail.Send(to: customerEmail, subject: “New Order”, body: body);

Paths

Use the ~ operator to get to the virtual root of the web site.  The virtual root is top level folder of your site, installed to here by default:

C:\Users\<YourUserName>\Documents\My Web Sites\Bakery

Where <YourUserName> is your Windows login name.  The Server.MapPath() method is also available, to help you when you need to convert physical paths to virtual paths for use on a web server.

Code constructs

Razor supports conditions and loops, so you can make decisions in your code.  You can use if blocks & switch blocks, for & foreach loops and while loops too.  Despite being a language that uses curly brace and is case sensitive, it’s very easy to read and write from a syntactic angle, as demonstrated here with a foreach loop, if statement and using the Mail object:

@foreach (var p in db.Query(“SELECT * FROM PRODUCTS”)) { … }

–and–

if (Mail.UserName.IsEmpty() || Mail.Password.IsEmpty() || Mail.From.IsEmpty()) {

        <h2>Please set up Mail!</h2><p>Please set your Hotmail Username, Password, and From Address in OrderSuccess.cshtml to send mail</p>

}

else {

    Mail.Send(to: customerEmail, subject: “New Order”, body: body);

    <h2>Thank you for ordering!</h2>

} 

Some other notable code constructs available in Razor are Try/Catch exception handling and arrays.  I just wanted to highlight a few of the popular ones here in this blog post. You can get a lot more information on the language features in the ASP.NET Web Pages with Razor Syntax eBook.

Helpers

Razor helpers allow you to encapsulate and condense complex tasks into a single line of code.  Some baked in helpers are used for …

  • Google Analytics
  • Facebook Integration
  • Twitter Integration
  • Sending Email
  • Validation
  • There’s lots more…

You can also create your own helpers, and there’ll be more helpers brought to you by Microsoft in the future.  Helpers are a big part of the Razor API.

The Razor API

This is where’s it at, in the API.  APIs (Application Programming Interfaces) contain functionality that you can tap into and use, rather than having to build it yourself.  The Razor API includes an extensive of helpers and activities like file uploading, data collection w/HTML Forms, charting, sending email, website analytics, etc…are all in the Razor API, and most only take a single or few lines of code to use.

You can browse the online API documentation here.

There’s More!

Of course, there’s a lot more you can do with Razor syntax; listed in this post are just some of the basics and features that you can take advantage of when building small, highly functional, easy to use web sites.