Intro to Razor View Engine


ASP.NET MVC 3 features the new Razor view engine. Like the older Web Forms view engine, Razor is a technology for building displays for a web application. However, the Razor syntax is designed to be cleaner and more readable than Web Forms code. Razor also provides a more fluid transition between code and markup. While Web Forms views use the .aspx extension, Razor views generated in C# have an extension of .cshtml.

With Razor, you can distribute view logic over a number of layout pages. Razor uses layout pages to hold markup that will be used across the site. Layout pages are similar to master pages in the older Web Forms programming model. One of the layout pages is the site-wide default layout (by default, this is called _Layout.cshtml). The default layout will typically contain the site's head section, metadata, body tags, and other site-wide content. Other layouts, applied locally, use the head and body elements from the default layout. Individual content views - loaded by the @RenderBody() and @RenderSection() methods - then fill out the content of the layouts.

When working with Razor views, you'll often see the @ sign. In most cases, this sign introduces C# code within HTML. When an @ expression is followed by curly brackets {}, the brackets will contain an entire C# code block.

For example, the following code block comes from a view included by default in a new MVC application.

@if (Request.IsAuthenticated
{
	<text>Welcome <strong>@User.Identity.Name</strong>!
	[ @Html.ActionLink("Log Off", "LogOff", "Account")
	]</text>

}
else
{
	@:[ @Html.ActionLink("Log Off", "LogOff", "Account") ]
}               

As in many Razor view pages, the code block contains both C# and HTML. The if/else statement instructs the view to serve a welcome message and a log-off link if the user is already logged in. Otherwise, the view will serve a log-on link. Markup is contained within HTML tags (e.g. , <strong> tag), and C# logic is initiated by the @ sign.

A few conditional statements are particularly useful for working in Razor:

  • @if
  • @if … else
  • @foreach
  • @while

In practice, these statements will be contextualized by parentheses (), curly braces {}, and var expressions. In Razor views, HTML markup can appear anywhere within C# expressions.