Building web pages using Microsoft's Razor engine

Les Pinter

About 10 years ago, several new technologies came along that revolutionized the web. HTML 5 and its huge increase in tag attributes (e.g. text-shadow) allowed developers to easily do many of the things that used to require JavaScript and PhotoShop. Libraries like jQuery and Angular.js made it much easier to build a rich user experience. But for me, the most interesting was the development of the Razor engine, a completely new mechanism for building web pages before they're sent out to the user's browser.

When you request a web page, you specify a URL (Universal Resource Locator). Originally, URLs often linked to static pages written in HTML (HyperText Markup Language), which was developed by Tim Berners-Lee at CERN in Switzerland in 1990. But shortly thereafter, the idea of letting a program running on the server write part or all of the HTML was implemented. These were originally called Active Server Pages, powered by either JavaScript or VBScript. But the latest incarnation used C#, and the technology is called Razor.

Razor is not a programming language; it's a server-side markup language that runs embedded code to emit HTML in addition to any HTML present in the page. The resulting page looks as if it had been statically coded. But it wasn't. A program wrote it.

If you write an active server page, using Razor or any other technology, you can tailor the output to suit your client. How? Based on their parameters, you add code that says "if they live here, include this; if they speak French, change language; if they're Republican, include this text."

You have several kinds of parameters: You can use their location, which the server can infer from their web request (it comes in loaded with bits of information - screen size, location, and others); you can read cookies on their computer; you can use information about them available from Google or Facebook; and you can ask them questions on one page, and then pass their answers as hidden fields from one page to the next. Get them to enter their email address, and you can write a thesis about them. And you can always look for certain phrases in any text related to them - FaceBook posts, emails, etc. - and slant the conversation in the way that will most appeal to them.

Getting Started

To create a Razor website, open Visual Studio and select New, Project, ASP.NET Web Site (Razor v3):

Fig. 1 - Starting a Razor project

The resulting project contains a number of files that play various roles. By default the "default.cshtml" page is the startup page for the website. In classic ASP.NET, code is stored in a code-behind file with the same name as its web page, but with ".cs" appended to the name of the .aspx page. But in .cshtml, the code and the HTML occupy a single file.

A cshtml page contains both HTML and C#. The C# exists to insert more HTML into the page. Here's a sample (from "Introduction to ASP.NET Web Programming Using the Razor Syntax (C#)" on the Microsoft web site):

<!-- Single statement blocks  -->
@{ var total = 7; }
@{ var myMessage = "Hello World"; }

<!-- Inline expressions -->
<p>The value of your account is: @total </p>
<p>The value of myMessage is: @myMessage</p>

<!-- Multi-statement block -->
    var greeting = "Welcome to our site!";
    var weekDay = DateTime.Now.DayOfWeek;
    var greetingMessage = greeting + " Today is: " + weekDay;
<p>The greeting is: @greetingMessage</p>

Adding data

You'll need a database. Right-click on the project file, select Add, New Item, and select SQL Server Database (C#) from the available options:

Fig. 2 - Add a database file

Once it's done, right-click on the .mdf file and select Server Explorer. Expand the tab, then select Tables. Right-click and select Add a table. Enter this:

CREATE TABLE [dbo].[Names] (
    [Id]    INT          IDENTITY (1, 1) NOT NULL,
    [Name]  VARCHAR (40) DEFAULT ('') NOT NULL,
    [Phone] VARCHAR (15) DEFAULT ('') NOT NULL,

Click on "Update" at the upper left of the Server Explorer window, and the table will be created. You can then select it, right-click again, and select Show Table Data data. Enter a few rows.

Structured Query Language (SQL) is the mechanism for manipulating table data. The SELECT query statement is used to retrieve table rows. Microsoft has created a Dynamic Link Library (DLL) called EntityFramework that, using IntelliSense, walks you through the process of creating a query. But you can also use simple SQL statements. That's what I've done in this example.

This is the code that prepares to retrieve your data:

   var db = Database.Open("MyDB");
   var selectQueryString = "SELECT * FROM Names";

Then all you have to do is format the output, using C# Razor syntax to iterate through the table and format each row. Here's the final version of default.cshtml:

      Layout = "~/_SiteLayout.cshtml";
      Page.Title = "Home Page";
      var x = "Today is " + DateTime.Now.ToShortDateString();

      var db = Database.Open("MyDB");
      var selectQueryString = "SELECT * FROM Names";

@section featured {

   <section class="featured">

      <div class="content-wrapper">

         <hgroup class="title">

               @foreach (var row in db.Query(selectQueryString))


...and here's what the output looks like:

Fig. 3 - the web page showing your data


There are few instances where you won't want to use dynamic web pages instead of static pages. Razor is a good technology for building dynamic websites, and if you're a C# programmer, you already speak the language. Check it out.