Introduction
ASP.NET MVC 3 brings us a new engine called Razor. Razor is an ASP.NET programming syntax that is used to create dynamic web pages with the C# and Visual Basic .NET languages. Razor was in development in June 2010 and was released in January 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 is 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 a semicolon.
- Variables are declared with the var keywords.
- C# is case-sensitive.
- C# files have the .cshtml extension.
- Strings are enclosed with quotation marks.
- A comment can be given as @*.........*@
Now let's take a simple example of printing Employee information using Razor. For this use the following steps.
Step 1. Open Visual Studio and click on File -> New -> Website.
Step 2. From C# select the ASP.NET MVC 3 Website (Razor); set the location and then click ok.
Step 3. The Default. cshtml file looks like this.
@{
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 information.
@* Multi-Statement Blocks *@
@{
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
If I remove the Layout option the output looks like.
Summary
In this article, I discussed how to use Razor syntax in ASP.Net.