What is Razor View Engine

The Razor view engine was introduced with ASP.NET MVC 3 and is the default view engine moving forward. This chapter focuses on Razor and does not cover the Webforms view engine.
Razor is the response to one of the most requested suggestions received by the ASP.NET MVC feature team — to provide a clean, lightweight, simple view engine that didn’t contain the “syntactic cruft” contained in the existing Web Forms view engine. Many developers felt all that syntactic noise required to write a view created friction when trying to read that view. This request was fi nally answered in ASP.NET MVC 3 with the introduction of the Razor view engine.
Razor provides a streamlined syntax for expressing views that minimizes the amount of syntax and extra characters. It effectively gets out of your way and puts as little syntax as possible between you and your view markup. Many developers who have written Razor views have commented on feeling the view code just flowing from their fingertips, akin to a mind-meld with their keyboard. This feeling is enhanced with the fi rst-rate IntelliSense support for Razor in Visual Studio.
Razor accomplishes this by understanding the structure of markup so that it can make the transitions between code and markup as smooth as possible. To understand what is meant by this, some examples will help. The following example demonstrates a simple Razor view that contains a bit of view logic:

@{
// this is a block of code. For demonstration purposes,
// we'll create a "model" inline.
var items = new string[] {"one", "two", "three"};
}
<html>
<head><title>Sample View</title></head>
<body>
<h1>Listing @items.Length items.</h1>
<ul>
@foreach(var item in items) {
<li>The item name is @item.</li>
}
</ul>
</body>
</html>

This code sample uses C# syntax, which means the file has the .cshtml file extension. Similarly, Razor views, which use the Visual Basic syntax, have the .vbhtml file extension. These file extensions are important, as they signal the code language syntax to the Razor parser.

Tagged . Bookmark the permalink.

Leave a Reply