[ASP.NET MVC] Views – Razor View

MVC3 introduced a new view engine called “Razor“. It is the recommended choice of a view and makes the legacy ASPX view engine obsolete. You can still use both engines but unless you are trapped in MVC2, Razor is the way to go.

1. Why New Engine

Razor is just a new syntax and in terms of functionality it does not provide significant progress compared  with the legacy ASPX view. Then why do we even bother with a new engine?

The ASPX view uses the “<% %>” syntax for code blocks. At first glance, MVC view code looks like old asp code. The most significant improvement of Razor is the simplified syntax.

2. Structure

Let’s look at the legacy ASPX file and the new Razor “cshtml” or “vbhtml” file.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Mvc3App.Models.Product>" %>
<!DOCTYPE html>
<html>
  <head runat="server">
    <title>WebFormView</title>
  </head>
  <body>
    <div>
      <%: (string)ViewData["Message"] %>
    </div>
  </body>
</html>
@model Mvc3App.Models.Product
@{ Layout = null; }
<!DOCTYPE html>
<html>
  <head>
    <title>RazorView</title>
  </head>
  <body>
    <div>
      @ViewBag.Message;
    </div>
  </body>
</html>

You can find some differences:

  • There is no @Page directive
  • The “Layout” Property is used. It is much like a master page.
  • @ syntax is used instead of <% %>

Razor view files are translated into classes and compiled, so they are not interpreted at runtime.

3. Razor Syntax Quick Reference

This is a quick reference about the Razor syntax with the Web Forms Equivalent:

  • Code Block
@{  string greeting = "Hello World"; }

<% string greeting = "Hello World"; %>
  • Expression (Html Encoded)
<span>@item.Property</span>

<span><%: item.Property %></span>
  • Expression (Html Unencoded)
<span>@Html.Raw(item.Property)</span>

<span><%= item.Property %></span>
  • if statement
@if ( condition )
{
  <span>@item.Property</span>
}
else
{
  <text>Plain Text</text>
}

<% if (condition) { %>
  <span><%: item.Property %></span>
<% } else { %>
  Plain Text
<% } %>
  • foreach statement
@foreach(var p in products)
{
  <li>@p.Name, $ @p.Price </li>
}

<% foreach(var p in products) { %>
  <li><%: p.Name%>, $ <%: p.Price%> </li>
<% } %>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s