ASP.NET MVC Framework has taken the .NET web development by storm. Most of the developers are now moving towards ASP.NET framework for web development. One of the challenges faced by the developers is to blend the server side code nicely in the HTML code. The Razor syntax addresses this problem and provides an easy way to use server side code in HTML.
Although you can express your intentions using the default classic ASP syntax but Razor syntax adds more clarity to the HTML side code. The Razor syntax will also become part of the Razor View Engine which will be released in the future.
At the point of this writing Razor syntax is only available in WebMatrix. WebMatrix is a free web development tool by Microsoft. You can download WebMatrix using the following URL:
Getting Started with Razor Syntax:
Create a new empty project in WebMatrix. By default WebMatrix is going to add "index.cshtml" and "Page.cshtml" files to the project. The following code is used to display the current time on the page using Razor syntax.
As you can see embedding server side code in HTML becomes so easy with Razor syntax. You no longer have to use the classic ASP syntax from the 80's.
You can even declare variables that can be used in the HTML as shown below:
You can also perform looping easily using the Razor syntax as shown in the code below:
You might be tempted to write the following code to display the title of the page.
Unfortunately, the above code is not going to work since the "this" object does not support the "Title" property. In order to see all the supported properties you can use the art of reflection as shown below:
The above code produces the following result:
You can even use few lines of code to list the items in the HttpCache as shown in the implementation below:
The screenshot shows the final result:
This article explained the basic syntax of the Razor templating engine. Razor allows to embedded server side code easily into the HTML. In the future articles we will focus on using Razor with the Razor View Engine.