DOCX

ASP.NET MVC Razor View Engine

By Grace Simpson,2014-09-20 15:08
9 views 0
ASP.NET MVC Razor View Engine

    Hands-On Lab ASP.NET MVC Razor

Lab version: 1.1.0

    Last updated: 9/20/2011

    Page 1

CONTENTS

    OVERVIEW ............................................................................................................................................. 3

    EXERCISE 1: CREATING A HOME PAGE VIEW USING RAZOR SYNTAX ........................................... 7

    Task 1 Creating a CSHTML Layout Page ....................................................................................... 10

    Task 2 Adding a View Template in Razor ..................................................................................... 13

    Task 3 Running the Application ................................................................................................... 17

    Task 4 Passing Parameters to a Layout Page ................................................................................ 17

    Task 5 Running the Application ................................................................................................... 18

    EXERCISE 2: USING MODELS IN RAZOR VIEWS .............................................................................. 19

    Task 1 Using the @inherits Directive ........................................................................................... 19

    Task 2 Running the Application ................................................................................................... 21

    Task 3 Adding a View Template in Razor ..................................................................................... 21

    Task 4 Running the Application ................................................................................................... 24

    Task 5 Creating Browse CSHTML View and Adding Details CSHTML View..................................... 25

    Task 6 Running the Application ................................................................................................... 27

    EXERCISE 3: CREATING AND CONSUMING RAZOR HELPERS ....................................................... 28

    Task 1 Consuming the Razor WebImage Helper ........................................................................... 28

    Task 2 Running the Application ................................................................................................... 31

    Task 3 Adding a WebGrid Helper to Browse View ........................................................................ 32

    Task 4 Running the Application ................................................................................................... 34

    Task 5 Creating a Custom Helper ................................................................................................. 35

    Task 6 Running the Application ................................................................................................... 37

    SUMMARY ............................................................................................................................................ 38

    Page 2

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. In this lab, we will use C# Razor with cshtml syntax.

    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:

    a. ‘@’ For a single code line/values:

    A single code line inside the markup:

    cshtml

    

     Current time is: @DateTime.Now

    

    Page 3

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

    cshtml

    @{

     var name = “John”;

     var nameMessage = "Hello, my name is " + name + " Smith";

    }

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

    cshtml

    @{

     @:The day is: @DateTime.Now.DayOfWeek. It is a great day!

    }

    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) {

    

Hello, the time is @DateTime.Now and this page is a postback!

} else {

    

Hello, today is:

@DateTime.Now

    }

    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;

    Conditionals and loops with inline HTML

    Here you will find examples of conditionals with inline html.

    Page 4

    ; If statement:

    cshtml

    <p>Single line Ifp>

    @if(result != ""){

     <p>Result: @resultp>

    }

cshtml

    <p>Code block Ifp>

@{

     var showToday = false;

     if(showToday){

     @DateTime.Today;

     } else{

     <text>Sorry!text>

     }

    }

    ; Foreach statement: cshtml

    <p> Single Line Foreach p>

    <ul>

    @foreach (var myItem in Request.ServerVariables){

     <li>@myItemli>

    }

    ul>

cshtml

    <p> Code block Foreach p>

    @{

     <h3>Team Membersh3> string[] teamMembers = {"Matt", "Joanne", "Robert",

    "Nancy"};

     foreach (var person in teamMembers)

     {

     <p>@personp>

     }

    }

    ; While statement:

    Page 5

    cshtml

    @{

     var countNum = 0;

     while (countNum < 50) {

     countNum += 1;

     <p>Line #@countNum: p>

     }

    }

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

     */

    }

    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)

    Page 6

    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

    Exercise 1: Creating a Home Page View Using Razor Syntax

    You have been working with ASP.NET C# language and HTML to create controllers and views. In this exercise, you will learn how to create MVC 3 views by using Razor syntax and Razor Layout Pages. In

    order to do that you will work with MVC Music Store web application to write its Home Page view in

    Razor.

    Razor Layout Pages

    A Razor Layout page is the equivalent of an ASP.NET Master Page. It defines the structure of a Web

    page by using HTML markup, and defines sections that will be filled with custom content. Web pages linked to a layout will only have to complete the sections with their own HTML. By using layout pages your site will have a consistent look that will also be easier to modify.

    Page 7

Razor Layout Pages Structure

Figure 1

    Layout and Web Pages

In essence, Razor Layout pages are HTML files that define a Body and additional sections by using the

    following instructions:

    ; @RenderBody(): Renders the content of a page that is not within any named sections.

    ; @RenderSection("mySectionName"): Renders the content of the section within the given

    name. Sections are mandatory by default, so each page linked to the template will have to

    declare them.

    ; @RenderSection("mySectionName", optional:true): Renders the content of an optional section.

    The pages that are linked to the template can omit the definition of an optional section.

Note: Optional sections allow us to use the same layout in pages that share part of the structure.

    However, this feature has to be carefully used if we want to keep a tidy and maintainable layout. In

    those cases, when the differences between the pages are significant, it will be better to add a new

    page layout instead of having a complex one.

Next you will see an example of a layout that defines two sections, one of them optional:

    Site.cshtml

    DOCTYPE html>

    <html>

    <head>

    <title>Layout Page Contenttitle>

     <link href="/Content/Site.css" rel="Stylesheet" type="text/css" />

    head>

    <body>

     <div id="header">

     @RenderSection("header")

     div>

    Page 8

     <div id="main">

     @RenderBody()

     div>

     <div id="footer">

     @RenderSection("footer", optional:true)

     div>

    body>

    html>

    Note: Optional sections can also be defined by using Razor directive IsSectionDefined("name"). The following line is equival to “@RenderSection("footer",optional:true)”:

     @if (IsSectionDefined("footer")) {

     @RenderSection("footer")

     }

Here is an example of a Razor Web page that links to the previous layout:

    cshtml

    @{

     LayoutPage = "~/Shared/Site.cshtml";

    }

@section header {

    <p>

     Razor example

    p>

    }

@section footer {

    <p>

     Optional page footer

    p>

    }

<div>

     Using Layout Pages Body content

    div>

Note: Most of the HTML elements were moved to the layout, leaving only the body and the section

    declarations.

    Page 9

Task 1 Creating a CSHTML Layout Page

    In this task, you will learn how to create a Layout page for Razor views that will work like the Site.master

    page from the ASP.NET MVC Fundamentals Hands-on Lab exercises.

    1. If not already open, start Microsoft Visual Web Developer 2010 Express from Start | All

    Programs | Microsoft Visual Studio 2010 Express | Microsoft Visual Web Developer 2010

    Express.

    2. In the File menu, choose Open Project. In the Open Project dialog, browse to Source\Ex01-

    CreatingAHomeRazorView\Begin, select MvcMusicStore.sln and click Open.

    3. Add a Layout Page. Because it is a shared resource you will create it under the /Views/Shared

    folder, in the same place of ASP.NET MasterPage. To do this, expand the Views folder and right-

    click the Shared folder. Select Add and then the New Item command.

    Figure 2

    Adding a new item to the solution

    4. In the Add New Item dialog box, select the MVC 3 Layout Page (Razor) template, located under

    Visual C#, Web template list. Change the name to Site.cshtml and click Add.

    Page 10

Report this document

For any questions or suggestions please email
cust-service@docsford.com