Published: 05 Nov 2010
By: Xianzhong Zhu
Download Sample Code

In the coming ASP.NET MVC 3.0 a lot of new good things will be added or enhanced. In this article, we are going to focus upon the new view engine Razor to see how it will simplify the view design.

Contents [hide]

The Experience ASP.NET MVC 3 Beta series

  • Part 1 In the coming ASP.NET MVC 3.0 a lot of new good things will be added or enhanced. In this article, we are going to focus upon the new view engine Razor to see how it will simplify the view design.
  • Part 2 In addition to the introduction of a new view engine Razor, ASP.NET MVC 3 Beta has also introduced numerous new HtmlHelpers, such as Chart, Crypto, WebGrid, WebImage, WebMail, etc. This article aims to introduce the two commonly-used new helper controls – WebGrid and Chart using relevant examples.
  • Part 3 In this installment, I'll first tell you a short story about unobtrusive JavaScript. Then, we'll delve into the unobtrusive client-side validation support. Finally, we will research into a more interesting story - the unobtrusive jQuery-Based Ajax support.
  • Part 4 In this article, we are going to continue to explore the other three important helpers - WebImage, WebMail, and Crypto.
  • Part 5 Starting from this article, let's explore some more advanced concepts and related utilizations associated with flexible Dependency Injection support introduced in ASP.NET MVC 3 Beta.
  • Part 6 In the last article, we've mainly discussed the new-styled DI support in ASP.NET MVC 3 Beta/RC in relation to the two new services - IControllerActivator and IViewPageActivator. Obviously, both of them are connected with controllers and views. In this article, however, we will shift our attention to the Model (generally called viewmodal in many blogs) related DI manipulations.
  • Part 7 Since ASP.NET MVC 1, CSRF (Cross Site Request Forgery) has been considered by introducing a set of anti-forgery helpers. In this article, we are to detail into CSRF related concepts and ASP.NET MVC's helper functions again CSRF.
  • Part 8 In this series of articles, we are going to explore as many as possible aspects of cache programming in the latest ASP.NET MVC 3 RC2 framework. And also, all the related samples have been tested against the latest ASP.NET MVC 3 RC 2.
  • Part 9 In the first part of this series, we've mainly explored Output Cache related issues. In this second part, however, we are going to delve into the general Data Cache topic.
  • Introduction

    In the coming ASP.NET MVC 3.0 a lot of new good things will be added or enhanced. In this series of articles aimed to ASP.NET MVC 3 Beta release, let's try to delve into some of the important points, such as the new view engine - Razor, new ASP.NET Web Pages Helper methods, enhanced Dependency Injection support, new support for Unobtrusive jQuery-based Ajax and jQuery validation, etc. by concrete samples.

    In this article, we are going to focus upon the new view engine Razor to see how it will simplify the view design.

    NOTE

    The development environments we'll utilize in this series are:

    1. Windows XP Professional (SP3);

    2. .NET 4.0;

    3. Visual Studio 2010;

    4. ASP.NET MVC 3 Beta (http://www.microsoft.com/downloads/en/details.aspx? FamilyID=0abac7a3-b302-4644-bd43-febf300b2c51);

    5. SQL Server 2005/2008;

    6. Northwind and pubs Sample Databases for SQL Server 2000 (URL: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=06616212-0356 -46A0-8DA2-EEBC53A68034&displaylang=en.You can easily use in the SQL Server 2005/2008).

    Introduction to Razor

    Razor is designed to be an alternate view engine for ASP.NET MVC. Initially introduced in WebMatrix and now shipped as part of ASP.NET MVC 3 Beta, Razor allows developers to replace the clunky <% %> syntax with a much cleaner coding model mainly around the sign @. Moreover, it provides some excellent features for Master Page scenarios, while at the same time you won't lose access to any features you are already familiar with, such as HTML helper methods.

    With the main aim to alleviate pain in authoring the view, the Razor view engine has been targeting the following characteristics.

    More compact and easier to use

    Razor aims to minimize the number of characters and keystrokes required in writing a view file, in support of a fast, fluid coding workflow. Unlike other existing template syntaxes, developers do not need to interrupt their coding to explicitly denote server blocks within the HTML. Razor parser is smart enough to infer this from the code.

    Razor is not a new language, whose syntax is mainly based on C#, and also supports the VB language. So, developers are able to use their existing C#/VB (or other) language and HTML skills with Razor. Moreover, Razor has brought an excellent template markup syntax that enables an awesome HTML construction workflow.

    To support IntelliSense and Unit Test

    For the time being, Visual Studio 2010 (and Visual Web Developer 2010) has not provided support for Razor syntax IntelliSense. But, according to Scott Guthrie, they will soon have full editor IntelliSense for it.

    Joyfully, Razor view engine implementation will support unit testing views. This may take a long journey, but such an accomplishment will surely drastically simplify the view design - one of the pains in MVC programming.

    Starting from the next section, I will introduce the elementary Razor syntax with mini examples.

    Razor Syntax Fundamentals

    On the whole, the Razor syntax is mainly around the "@" sign. Let's look at some elementary examples. Razor syntax is designed around one primary goal: make code and markup flow together with as little interference from control characters as possible.

    The Razor parser has three "actors": The Core parser, the Markup parser and the Code parser. All these three components work together to parse a Razor document.

    Create a sample project Sketch

    Suppose you've installed ASP.NET MVC 3 Beta. Now, start up your Visual Studio 2010 IDE to create an ASP.NET MVC 3 web application, naming it MVC3_RazorSyntax (see Figure 1 below).

    Figure 1: Create a sample project using ASP.NET MVC 3 Web Application template

    Create a sample project using ASP.NET MVC 3 Web Application 

template

    After clicking the OK button, another dialog box appears to prompt you to select the proper template and view engine, as shown in Figure 2.

    Figure 2: Select our interested Razor view engine

    Select our 

interested Razor view engine

    In our case, we select the template "Internet Application" and View Engine as Razor. And for simplicity, we don't want to add the related unit test project.

    Common expression

    Razor introduces many familiar operators as C# and VB, such as:

    . () [] = ! == != <> <= >= + - * / && || += -=

    To create a common Razor expression, you should embrace it using a pair of parentheses as the following:

    Variables & data types

    Use the var keyword to declare variables, or use the classic typed syntax. The new operator is also supported.

    Razor supports all the standard .NET framework simple data types and allows developers to take advantage of consuming objects and collections, using the classic dot notation, as shown below:

    Moreover, Razor also allows using temporary variables. For example:

    Please notice that the variable names within @{} are case-sensitive.

    Single statement block

    For single statement, you just need to use the curly bracket to enclose it with the prefix @ sign. For example:

    Enclose literal string values in double quotation marks

    A string is a sequence of characters that are treated as text. To specify a string, you should enclose it in double quotation marks, such as:

    If the string contains a backslash character (\) or double quotation marks, use a verbatim string literal that is prefixed with the @ operator.

    The rendering result looks like this:

    The path is: C: \MyFolder\

    To embed double quotation marks, use a verbatim string literal and repeat the quotation marks:

    The rendering result looks like this:

    The person said: "Hello, today is Monday."

    NOTE

    As with your familiar C#/VB, in Razor:

    1. Extra spaces in a statement (and outside of a string literal) do not affect the statement.

    2. In general, a line break in a statement has no effect on the statement, and you can wrap statements for readability. However, you can't wrap a line in the middle of a string literal.

    Multi-line blocks

    As for multiple lined blocks, we also use curly brackets to enclose them, like the following:

    The rendering result looks like this:

    The greeting is: Welcome to our site! Today is: Saturday

    Note according to Razor syntax, we have to:

    • Use the curly braces to enclose the expression or statement
    • Statements within the curly braces should end with a semicolon
    NOTE

    When displaying content in a view using the @ character (as in the preceding examples), ASP.NET will HTML-encodes the output. This replaces reserved HTML characters (such as < and > and &) with codes that enable the characters to be displayed as characters in a web page instead of being interpreted as HTML tags or entities. In this way, you can avoid exposing a page to security risks.

    Comments

    For ASP.NET Razor comments, you start the comment with @* and end it with *@. The comment can be on one line or multiple lines:

    Here is a comment within a code block:

    Here is the same block of code, with the line of code commented out so that it will not run:

    Here is a comment block example with multiple lines:

    Note inside a code block, as an alternative to using Razor comment syntax, you can use the commenting syntax of the programming language you are using, such as C#:

    For HTML markup, you can create a familiar HTML comment:

    HTML comments start with <!-- characters and end with -->. You can use HTML comments to surround not only text, but also any HTML markup that you may want to keep in the page but don't want to render.

    The HTML comment below will hide the entire content of the tags and the text they contain:

    Note that unlike Razor comments, HTML comments are rendered to the page and the user can see them by viewing the page source.

    The “text” label

    In cases where you have content that you want to render to the client without a wrapping tag, you can wrap nested content with a <text> block:

    Differentiate the symbol @ intelligently

    Razor can differentiate the symbol @ within an email address from the one that identifies the Razor statement or command.

    The rendering result looks like this:

    mail scottgu@microsoft.com telling: 2010-10-30 20:04:01.

    In cases where the content is valid as code as well (and you want to treat it as content), you can explicitly escape out @ characters by typing @@. For example:

    The associated rendering result looks like this:

    Could you tell the function of the symbol @ in the Razor statement ” @DateTime.Now”?

    Compound statements

    Now, let's look into the compound statements related syntaxes.

    1. Condition statements

    Example 1:

    Example 2:

    2. for loop statement

    The for loop statement is quite like that in C#/VB, as shown below:

    3. foreach statement

    The foreach statement in Razor is also nothing peculiar. Consider the following example:

    4. while loop statement

    Consider the following example:

    The associated rendering result looks like this:

    The value of iCounter is 5.

    4. switch statement

    The switch statement in Razor is also nothing special. Consider the following example:

    The associated rendering result looks like this:

    Since it is Wednesday, the message for today is: Wild Wednesday is here!

    5. try...catch...

    As you've already known, in a great degree current ASP.NET view programming goes back to the age of ASP. Therefore, it's possible for you to embed numerous pieces of code block inside the view itself. This, in some degree, increases the difficulty in debugging this kind of server-side code. For this, ASP.NET MVC also introduces the try...catch...support. Look at the following example:

    It's nearly the same as that in .aspx.cs files in the Web Forms environment, isn't it?

    Now that you've gotten familiar with the commonly- used Razor grammar, let's shift out attention to some advanced support in Razor.

    Layout Files Support

    As with the ASP.NET Master Page, Razor also introduces a similar concept - layout page - which allows you to define a common site template, and then inherit its look and feel across all the views/pages on your site.

    In the case of the Razor view engine, the term Master page isn't used as in the aspx view engine - they are renamed layout page. However, it is still similar to the ASP.NET master page.

    Now, let's look at the default layout page called _Layout.cshtml, which contains the following.

    First note that in the head area we used @View.Title to allow us to replace the title with a value supplied by the related individual view. Then, we used Url.Content to properly find the required css file.

    Next, we are using a partial view, like this:

    Partial views are quite similar to user controls in the traditional ASP.NET world, which can have their own view data so they can be reused independently of their containing view. Partial view is a big step toward building reusable components.

    Finally, comes the most important part of the layout page - @RenderBody(). When using layout pages with Razor, we can add the @RenderBody method, which means where we want to have our "main content" of our content page located herein.

    Well now, it is a simple thing to put the above layout page _Layout.cshtml into use.

    In the Home controller, add a simple action named MyView.

    Afterwards, right click the action MyView to add a new related view, still with the view name being MyView (see Figure 3). Note the view engine is Razor and we've used the default option - use the layout page _Layout.cshtml as the Master page.

    Then, modify the file MyView.cshtml using the following content:

    Listing 1: A sample Razor page using the layout page

    Have you noticed the Layout keyword? It's the key to have a sub view inherit from the layout file. About the new ASP.NET MVC 3 Beta introduced @model directive, we'll discuss a moment later.

    Now, press Cttrl+F5 to launch the MVC application. Then, if you enter the route "home/myview" at the end of the default url and press ENTER, you will see something like Figure 4 below.

    Note, for more useful things, such as Section, Optional Section, and passing data to layout pages, about layout files support under the Razor environment, you can refer to the tutorial titled "Creating a Consistent Look" at http://www.asp.net/webmatrix/tutorials/3- creating-a-consistent-look. Note that some assets have changed in the current Beta version. Obviously, you can also create as many as possible additional content pages that can share the same layout page as _Layout.cshtml.

    Reuse HTML Helpers

    In this section, let's look at how we can create re-usable "HTML helpers" enabling us to cleanly encapsulate HTML generation functionality to be re-used across our site. A helper is a component helping you accomplish a task using a single line of code. ASP.NET includes many ready-to-use helpers.

    First of all, let's say a few words about the familiar built-in HTML extensions.

    Built-in HTML extension methods

    All of the existing HTML extension methods built with ASP.NET MVC still work using the "Razor" view engine, nearly without any code changed. For example:

    Listing 2: Unchanged HTML extension methods with Razor

    The Razor API includes an extensive of helpers and activities like file uploading, data collection w/HTML Forms, charting, sending email, website analytics, etc...most of which only take a single or few lines of code to use. Some of these important components in the Razor API will be delved into in another article.

    Create custom Helper method

    This part shows you how to create a custom helper that creates a reusable product list. To do this, follow the steps listed below:

    1. Under the root folder of the MVC project create a new sub directory App_Code.

    2. Right click the App_Code folder and selct "Add | New Item...".Then in the "Add New Item" dialog box, select the template "MVC 3 View Page (Razor)" to create a new .cshtml file called MyHelpers.cshtml.

    3. Replace any existing content with the following:

    The above code uses the @helper syntax to declare a new helper named ProductListing. This particular helper lets you pass it a parameter named products of the generic type List<Product>. Notice that the file itself is named MyHelpers.cshtml, but the helper is named ProductListing. As a supplement, you can also put multiple custom helpers into a single view file.

    Till now, we can re-use the helper from any view or page in your site. Let's make a related example.

    4. Create a controller named ProductsController.

    5. Right click the action Index to add a new strongly-typed view Index, select the view data class as RazorSyntax.Models.Products, and Razor as the view engine.

    6. Use the following code to replace the original content of the file Index.cshtml:

    To call the helper you created, use @ followed by the file name where the helper is, a dot, and then the helper name. (If you had multiple folders in the App_Code folder, you could use the syntax @FolderName.FileName.HelperName to call your helper within any nested folder level). The text that you add in quotation marks within the parentheses is the text that the helper will display as part of the note in the web page.

    Note herein how the helper ProductListing() is able to define parameters. This enables you to pass any parameters you want to them. Also, note here we can take full advantage of existing languages features like optional parameters, nullable types, generics, etc).

    Note that with the ASP.NET MVC 3 Beta a new feature has been added - the @model directive. The @model directive provides a cleaner and more concise way to reference strongly-typed models from view files.

    Now, we can just write @model StrongModelType at the top of our Razor view file, and we do not need to have a @inherits or specify a view base class anymore.

    At last, save the above view page and press Ctrl+F5 to run the sample project. Input the route "products/index" at the end of the default url, press ENTER, and you will see a running-time snapshot as shown in Figure 6.

    As you may have guessed, there's a lot more you can do with Razor syntax - in this article we've only scratched the surface.

    NOTE

    There has been already an excellent tool named "Razor Syntax Highlighter" at http://visualstudiogallery.msdn.microsoft.com/en-us/8dc77b9c- 7c83-4392-9c46-fd15f3927a2e which support Razor syntax highlight. To use it, just download the tiny extension and double click it to have it installed. Once you start up your Visual Studio Ultimate and open a .cshtml file, it will affect the Razor syntax. Regrettably, the advanced IntelliSense effect maybe waits to the next release of VS or its Patches.

    Summary

    In this installment, we've looked over parts of the major features of the Razor view engine in the ASP.Net MVC 3 Beta release via scraps of samples. As you've seen, Razor is a clean, expressive way to build MVC views and a welcome addition to the list of available MVC view engines.

    But, there are at least two points worth your noticing. First, we've only introduced a Beta release - your code works today in the Razor view engine doesn't mean it will work tomorrow. Second, there is currently limited support in Visual Studio 2010 for Razor yet - no friendly IntelliSense for now. But, surely it will come in no time.

    The Experience ASP.NET MVC 3 Beta series

  • Part 1 In the coming ASP.NET MVC 3.0 a lot of new good things will be added or enhanced. In this article, we are going to focus upon the new view engine Razor to see how it will simplify the view design.
  • Part 2 In addition to the introduction of a new view engine Razor, ASP.NET MVC 3 Beta has also introduced numerous new HtmlHelpers, such as Chart, Crypto, WebGrid, WebImage, WebMail, etc. This article aims to introduce the two commonly-used new helper controls – WebGrid and Chart using relevant examples.
  • Part 3 In this installment, I'll first tell you a short story about unobtrusive JavaScript. Then, we'll delve into the unobtrusive client-side validation support. Finally, we will research into a more interesting story - the unobtrusive jQuery-Based Ajax support.
  • Part 4 In this article, we are going to continue to explore the other three important helpers - WebImage, WebMail, and Crypto.
  • Part 5 Starting from this article, let's explore some more advanced concepts and related utilizations associated with flexible Dependency Injection support introduced in ASP.NET MVC 3 Beta.
  • Part 6 In the last article, we've mainly discussed the new-styled DI support in ASP.NET MVC 3 Beta/RC in relation to the two new services - IControllerActivator and IViewPageActivator. Obviously, both of them are connected with controllers and views. In this article, however, we will shift our attention to the Model (generally called viewmodal in many blogs) related DI manipulations.
  • Part 7 Since ASP.NET MVC 1, CSRF (Cross Site Request Forgery) has been considered by introducing a set of anti-forgery helpers. In this article, we are to detail into CSRF related concepts and ASP.NET MVC's helper functions again CSRF.
  • Part 8 In this series of articles, we are going to explore as many as possible aspects of cache programming in the latest ASP.NET MVC 3 RC2 framework. And also, all the related samples have been tested against the latest ASP.NET MVC 3 RC 2.
  • Part 9 In the first part of this series, we've mainly explored Output Cache related issues. In this second part, however, we are going to delve into the general Data Cache topic.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Xianzhong Zhu

    I'm a college teacher and also a freelance developer and writer from WeiFang China, with more than fourteen years of experience in design, and development of various kinds of products and applications on Windows platform. My expertise is in Visual C++/Basic/C#, SQL Server 2000/2005/2008, PHP+MyS...

    This author has published 81 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
    A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
    jQuery Mobile ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    Exception Handling and .Net (A practical approach)
    Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
    JQuery Mobile Widgets Overview
    An overview of widgets in jQuery Mobile.
    Book Review: SignalR: Real-time Application Development
    A book review of SignalR by Simone.
    Top
     
     
     

    Please login to rate or to leave a comment.