TOC

The community is working on translating this tutorial into Thai, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Razor:

Introduction

When Microsoft first created the ASP.NET MVC framework, it used WebForms pages to display content. However, WebForms wasn't as flexible as people were used to from other MVC frameworks - it had too much overhead in the form of ViewState, server controls etc. Therefore, Microsoft decided to implement a much simpler and more lightweight language/view engine for the MVC framework. They called it Razor and it was released in January 2011, as a part of ASP.NET MVC version 3.

Razor allows you to write in various "dialects", based on your favorite .NET language. In this tutorial, we will be focusing on the C# version of Razor, but you can use Razor with VB.NET as well.

Why use Razor?

The biggest advantage of the Razor is the fact that you can mix client-side markup (HTML) with server-side code (e.g C# or VB.NET), without having to explicitly jump in and out of the two syntax types. For instance, consider this example of a page in ASP.NET WebForms:

<p>Hello, world - my name is <%= name %> and the current date is: <%= DateTime.Now.ToString() %></p>

In Razor, you can reference server-side variables etc. by simply prefixing it with an at-character (@). The above example, written with Razor instead, would look like this:

<p>Hello, world - my name is @name and the current date is: @DateTime.Now.ToString()</p>

Now obviously this basic example doesn't save you a ton of keystrokes, but in the long run, this makes it a lot easier and much faster to build your pages and combine markup with code. This becomes more obvious when you want to do something slightly more advanced, like making a conditional statement in your view:

<%
if(Request.QueryString["test"] != null)
{
%>
    <p>Lots of markup here...</p>
    <p>Test value: <b><%= Request.QueryString["test"] %></b></p>
    <p>And even more here...</p>
<%
}
%>

In Razor, you could achieve the same like this:

@if(Request.QueryString["test"] != null)
{
    <p>Lots of markup here...</p>
    <p>Test value: <b>@Request.QueryString["test"]</b></p>
    <p>And even more here...</p>
}

Summary

As you can see from the above examples, Razor simply makes it a whole lot easier to combine markup and code. In the next couple of chapters, we'll take a deeper look into the Razor syntax and how it works.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!