ASP.NET MVC 3 Razor

Version: 1.1.0

Description

ASP.NET MVC 3 introduces the new view engine Razor, which was conceived to simplify the current syntax used in ASP.NET web pages. In this lab you will learn how to create Razor views inside an MVC solution. In the beginning of this Lab you will first get familiar with Razor syntax and its features: general rules, code blocks, inline HTML and layout pages. Once you have learned the basics, in Exercise 2 you will add Razor views in the MVC Music Store solution to provide the same functionality you have in ASP.NET views, but with a clearer and reduced code. At the end of this lab, in Exercise 3, you will learn how to create and consume third party Razor Helpers.

Overview

Note:
This Hands-on Lab assumes you have basic knowledge of ASP.NET MVC. If you have not used ASP.NET MVC before, we recommend you to go over ASP.NET MVC Fundamentals Hand-on Lab.

ASP.NET MVC 3 introduces the new view engine Razor, which was conceived to simplify the current syntax used in ASP.NET web pages. In this lab, you will learn how to create Razor views inside an MVC solution.

In the beginning of this Lab you will first get familiar with Razor syntax and its features: general rules, code blocks, inline HTML and layout pages. Once you have learned the basics, in Exercise 2 you will add Razor views in the MVC Music Store solution to provide the same functionality you have in ASP.NET views, but with a clearer and reduced code.

At the end of this lab, in Exercise 3, you will learn how to create and consume Razor Helpers to use images, grids and custom functionality.

About Razor View Engine

Many ASP.NET Web pages have C# or VB code blocks in the same place as HTML markup. In some occasions this combination is uncomfortable for writing and delimiting code. To deal with that problem, Razor was designed as an easy to learn, compact and expressive view engine that enables a fluid coding workflow.

Razor is not a new programming language itself, but uses C# or Visual Basic syntax for having code inside a page without ASP.NET delimiter: <%= %>. Razor file extension is ‘cshtml’ for C# language, and ‘vbhtml’ for Visual Basic.

Razor Syntax – The fundamentals

Before getting introduced to Razor you should first know some simple rules that will help you understand how to write HTML with C# or Visual Basic in the same page:

  1. @’ is the magic character that precedes code instructions in the following contexts:
    1. ‘@’ For a single code line/values:

      A single code line inside the markup:

      cshtml

      <p> Current time is: @DateTime.Now </p>

      vbhtml

      <p> Current time is: @DateTime.Now </p>

    2. ‘@{ … }’ For code blocks with multiple lines:

      cshtml

      @{ var name = “John”; var nameMessage = "Hello, my name is " + name + " Smith"; }

      vbhtml

      @Code Dim name = “John” Dim nameMessage = "Hello, my name is " + name + " Smith" End Code

    3. ‘@:’ For single plain text to be rendered in the page.

      cshtml

      @{ @:The day is: @DateTime.Now.DayOfWeek. It is a <b>great</b> day! }

      vbhtml

      @Code @:The day is: @DateTime.Now.DayOfWeek. It is a <b>great</b> day! End Code

  2. HTML markup lines can be included at any part of the code:

    It is no need to open or close code blocks to write HTML inside a page. If you want to add a code instruction inside HTML, you will need to use ‘@’ before the code:

    cshtml

    @if(IsPost) { <p>Hello, the time is @DateTime.Now and this page is a postback!</p> } else { <p>Hello, today is: </p> @DateTime.Now }

    vbhtml

    @If IsPost Then @<p>Hello, the time is @DateTime.Now and this page is a postback!</p> Else @<p>Hello, today is: </p> @DateTime.Now End If

  3. Razor uses code syntax to infer indent:

    Razor Parser infers code ending by reading the opening and the closing characters or HTML elements. In consequence, the use of openings “{“ and closings “}” is mandatory, even for single line instructions:

    cshtml

    // This won’t work in Razor. Content has to be wrapped between { } if( i < 1 ) int myVar=0;

    vbhtml

    // This won’t work in Razor. Content has to be wrapped between { } If i < 1 Then Dim myVar As int =0 End if

Conditionals and loops with inline HTML

Here you will find examples of conditionals with inline html.

  • If statement:

    cshtml

    <p>Single line If</p> @if(result != ""){ <p>Result: @result</p> }

    vbhtml

    <p>Single line If</p> @If result <> "" Then @<p>Result: @result</p> End If

    cshtml

    <p>Code block If</p> @{ var showToday = false; if(showToday){ @DateTime.Today; } else{ <text>Sorry!</text> } }

    vbhtml

    <p>Code block If</p> @Code Dim showToday = false If showToday Then @DateTime.Today Else @<text>Sorry!</text> End if End Code

  • Foreach statement:

    cshtml

    <p> Single Line Foreach </p> <ul> @foreach (var myItem in Request.ServerVariables){ <li>@myItem</li> } </ul>

    vbhtml

    <p> Single Line Foreach </p> <ul> @For Each myItem in Request.ServerVariables @<li>@myItem</li> Next myItem </ul>

    cshtml

    <p> Code block Foreach </p> @{ <h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert", "Nancy"}; foreach (var person in teamMembers) { <p>@person</p> } }

    vbhtml

    <p> Code block Foreach </p> @Code @<h3>Team Members</h3> Dim teamMembers() As String = {"Matt", "Joanne", "Robert", "Nancy"} For Each person in teamMembers @<p>@person</p> Next person End Code

  • While statement:

    cshtml

    @{ var countNum = 0; while (countNum < 50) { countNum += 1; <p>Line #@countNum: </p> } }

    vbhtml

    @Code Dim countNum = 0 Do While countNum < 50 countNum += 1 @<p>Line #@countNum: </p> Loop End Code

Comments

Comments in Razor are delimited by @**@. If you are inside a C# code block, you can also use // and /* */ comment delimiters.

cshtml

@* A Razor Comment *@ @{ //A C# comment /* A Multi line C# comment */ }

FakePre-96806ace19d04550857f68186b2ef1a0-ed015f580aee45cb9529c40e8d858e7b

vbhtml

@* A Razor Comment *@ @Code //A C# comment /* A Multi line C# comment */ End Code

FakePre-eb5ca788f81f48c28bee7413fda32d31-950c894447fc4ac3b6b1bbd66b05d21c

In this Hands-on Lab, you will learn how to:

  • Create Razor Layout page templates
  • Create MVC Views using Razor syntax
  • Create and consume Razor Helpers

System Requirements

You must have the following items to complete this lab:

  • ASP.NET and ASP.NET MVC 3
  • Visual Studio 2010 Express
  • SQL Server Database (Express edition or above)

    Note:
    You can install the previous system requirements by using the Web Platform Installer 3.0: http://go.microsoft.com/fwlink/?LinkID=194638.

Exercises

This Hands-On Lab is comprised by the following exercises:

  1. Exercise 1: Creating a Home page view using Razor syntax
  2. Exercise 2: Using Models in Razor views
  3. Exercise 3: Creating and Consuming Razor Helpers from a View

Estimated time to complete this lab: 30 minutes.

Note:
Each exercise is accompanied by an End folder containing the resulting solution you should obtain after completing the exercises. You can use this solution as a guide if you need additional help working through the exercises.

Next Step

Exercise 1: Creating a Home page view using Razor syntax