Introduction to Microsoft ASP.NET MVC 3 Razor View Engine

Introduction

ASP.NET MVC 3 brings us a new engine called Razor. Razor is an ASP.NET programming syntax that is used to create the dynamic web pages with the C# and Visual Basic .NET languages. Razor was in development in June 2010 and was released in January of 2011. Razor is a simple-syntax view engine and is a part of ASP.NET MVC 3 and the Microsoft WebMatrix tool set. Or we can say that Razor is the markup syntax for adding server-based code to web pages. It is easier to learn and use. It much like a server-side scripting language. The file extension of Razor files is .cshtml.

Some Main Syntax of Razor are:

  • The code blocks in Razor are enclosed in @{.........}.
  • All the inline expressions like variables and functions start with @.
  • The code statement ends with the semicolon.
  • Variables are declared with the var keywords.
  • C# is case sensitive.
  • C# files have the .cshtml extension.
  • Strings are enclosed with the quotation marks.
  • A comment can be given as @*.........*@
Now let's take a simple example of printing the Employee information using Razor. For this use the following steps:
 
Step 1: Open Visual Studio and click on File -> New -> Website.

razor1.gif

Step 2 :  From C# select the ASP.NET MVC 3 Website (Razor); set the location and then click ok.

razor2.gif

Step 3 : The Default.cshtml file looks like:

@{ 

    Layout = "~/_SiteLayout.cshtml";

    Page.Title = "Welcome to my Web Site!";

}

<p>

    ASP.NET Web Pages make it easy to build powerful .NET based applications for the web.

</p>

Hear the @{ ......} sign represents the Razor syntax.

Step 4 : Write the following code in order to display the user infromation.
 

@*Multi-Statement Bloks*@

@{ 

    Layout = "~/_SiteLayout.cshtml";

    Page.Title = "Employee Information";

    var name = "Richa Garg";

    var address = "Delhi";

    var id = 12;

   

}

@*Inline-expression*@

<p>

    The Name of the Employee is:@name</p>

<p>

    The Address of the Employee is: @address</p>

<p>

    The Id of the Employee is:@id</p>

In this example the layout works the same as the master files in ASP.NET. Now to run this application press F5.

Output

razor3.gif

If I remove the Layout option the output looks like:

razor4.gif

 

Summary : In this article I discussed how to use Razor syntax in ASP.Net.

 

Up Next
    Ebook Download
    View all
    Learn
    View all