MVC 4 Razor View Engine Syntax

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.
MVC 4 Razor View Engine Syntax

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


  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
    */
}
vbhtml
@*
    A Razor Comment
*@
@Code
    //A C# comment
    /* A Multi
         line C# comment
    */
End Code

We had several design goals in mind as we prototyped and evaluated “Razor”:

  • Compact, Expressive, and Fluid: Razor minimizes the number of characters and keystrokes required in a file, and enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote server blocks within your HTML. The parser is smart enough to infer this from your code. This enables a really compact and expressive syntax which is clean, fast and fun to type.
  • Easy to Learn: Razor is easy to learn and enables you to quickly be productive with a minimum of concepts. You use all your existing language and HTML skills.
  • Is not a new language: We consciously chose not to create a new imperative language with Razor. Instead we wanted to enable developers to use their existing C#/VB (or other) language skills with Razor, and deliver a template markup syntax that enables an awesome HTML construction workflow with your language of choice.
  • Works with any Text Editor: Razor doesn’t require a specific tool and enables you to be productive in any plain old text editor (notepad works great).
  • Has great Intellisense: While Razor has been designed to not require a specific tool or code editor, it will have awesome statement completion support within Visual Studio. We’ll be updating Visual Studio 2010 and Visual Web Developer 2010 to have full editor intellisense for it.
  • Unit Testable: The new view engine implementation will support the ability to unit test views (without requiring a controller or web-server, and can be hosted in any unit test project – no special app-domain required).

Related Post


MVC 4 Razor View Engine Syntax MVC 4 Razor View Engine Syntax Reviewed by Bhaumik Patel on 10:33 PM Rating: 5