Introduction to a New View engine of "Razor"-ASP. NET

Source: Internet
Author: User
Tags visual studio 2010

On msdn, I saw Scott write a new view engine about MVC. I think it is very powerful and can effectively solve the current MVC view.CodeCompilation is cumbersome and is expected to be officially released.

 

[Original article] introducing "Razor"-A New View engine for ASP. NET

[Original article publication date] July 02,201 0 pm

One of the jobs my team is currently working on is to add a new view engine for ASP. NET.

ASP. net mvc has always supported the concept of "view engine"-pluggable modules using templates with different syntaxes. Currently, the "default" view engine of ASP. net mvc is the. aspx/. ascx/. master file template used by ASP. NET web forms. Other popular ASP. net mvc view engines include spark and nhaml.

We are building a new view engine that is optimized in HTML generation and uses a code-focused template solution. Its development code is "Razor", and the first beta version will soon be released.

Design Objectives

When designing and evaluating razor, we should keep in mind the following goals:

·Compact, expressive, and smooth: Razor tries to reduce the number of characters to be typed in a file, giving you a quick coding experience. Unlike the syntax of most templates, you don't have to interrupt the pleasure of coding because you need to mark server-side code blocks in HTML. The Code Analyzer is smart enough to infer from your code whether it is server-side code. This makes the concise and expressive syntax input clean, fast, and interesting.

·Easy to use: Razor is very easy to use. You only need to know a few new things to learn about it and use your existingProgramming LanguageAnd HTML knowledge is enough.

·Not a new Programming Language: Try to avoid creating a new imperative language for Razor. Instead, we wantProgramYou can use razor only by using the existing C #/Vb (or other) programming language knowledge, but in the programming language you choose, provides a great HTML Tag syntax generated based on templates.

·You can use any text editor to write: Razor does not require any special tools. It can also be efficiently programmed using an antique Text Editor ("Notepad" is good ).

·Good smart sensor input prompt: Although razor is not designed for a tool or code editor, it still has a great smart reminder feature in Visual Studio. Visual Studio 2010 and Visual Web Developer 2010 will be upgraded to provide the complete editor smart prompt function.

·Easy unit test: The New View engine allows you to perform unit tests on views without the need for controllers or web servers, in addition, it can be included in any unit test project-no separate application domain is required ).

Over the past few months, we have been using razor to write programs and invited volunteers (including several non-. NET web programmers) to study usability. People who have used it evaluate it well.

Flexible selection space

One of ASP. NET's most popular features is that most components are pluggable. If you find that one component is not easy to use, you can change it to another component at any time.

ASP. the next version of net MVC will include a new "Add-> View" dialog box, which allows you to easily select the syntax you want when creating a new view template file. It also allows you to choose any view engine installed on the machine-select the most natural view solution you feel:

Razor will be one of the built-in view engines of ASP. net mvc. All view assist methods and programming model features support both the razor and. aspx view engines.

You can also use view templates written by multiple view engines in a single site or program. For example, you can write some views. aspx file, some use. cshtml or. vbhtml files (C # and VB versions of razor), and spark or nhaml files are used. You can also include a partial view template written with another engine in a view engine. In short, you have flexible options.

Razor "Hello World"

Razor allows you to add server code to change static html pages (or any text content) to dynamic pages. A core design concept of razor is to make the coding process smoother, and the server code can be quickly added to HTML tags as long as the minimum number of buttons.

Let's create a simple example: "Hello world". The final output is shown in:

Use. aspx "code fragments[II]".

If you use existing ASP.. net. in the above "Hello World" example, we need to use "<% = %>" in the HTML tag to mark "code fragments ":

After careful observation, we can find that each part of the code in the previous example requires five characters ("<% = %>") to indicate the start and end position of the Code. In addition, there are a few characters that are not particularly good on the keyboard (especially the "%" key-it is located in the middle and upper part of most of the keyboard ).

Use razor syntax

In razor, you only need to use the "@" character to mark the beginning of the code block, which is different from the "<%>" code chunk, razor does not need to explicitly specify the end position of the code block:

The razor analyzer understands the C # Or VB syntax used in the code block-that's why we didn't need to explicitly close the code block in the previous example. Razor can automatically identify the preceding statements as independent code blocks and quietly close them for us.

Let's see, even a trivial example like "hello World" saves us 12 keyboard hits. In addition, the "@" character on the keyboard is easier to press than the "%" character, making it faster and smoother.

Example of loop and embedded HTML

Let's take a look at another simple scenario, such as listing some items (and marking the price next to each item ):

Written with. aspx "code chunks"

If the existing. aspx tag Syntax of ASP. NET is used, we may need to write code similar to the following to dynamically generate a <ul> list, which contains the <li> element indicating each item:

Use razor syntax

The following code generates the same output version of razor:

Note how the "@" symbol above starts a "foreach" loop and embeds a line of HTML statements containing code blocks in the loop. Because the razor analyzer knows the C # syntax we use in the code block, it can identify the content in the <li> label should be included in the foreach code block and process them cyclically. It even knows that the "}" at the end ends the foreach loop.

Razor is very clever. It can also identify @ P. Name and @ P. Price in the <li> label as server-side code and execute them at each loop. In addition, please note that razor can export the end position of the @ P. Name and @ P. Price code blocks when HTML and code are mixed.

You don't need to add many opening/closing tags to your template to write your code.

If code block and multi-line statements

The following are several other common scenarios:

If statement

Keep upForeachFor example, you can embed content (or other C # Or VB elements) in the IF statement without explicitly specifying the start and end positions of the code block. For example:

Multi-line statements

You can use "@ {code}" to mark multiple lines of statements as follows:

Note that in the preceding example, a variable can be referenced by multiple code blocks-the variable "message" is defined in the "@ {}" block containing multi-line statements, but it can also be used by @ message code block. This is similar to the syntax of "<%>" and "<% = %>" in the. aspx file.

Multi-symbol statement

The "@ ()" syntax allows multiple symbols in the code block. For example, we can rewrite the code block connecting strings and numbers in the previous example using the "@ ()" code block as follows:

Integrate code and content

The razor parser has many built-in language intelligence-dirty work to help you.

In HTML, does it affect the use of the "@" symbol in email addresses and other places?

In most cases, the razor parser has the ability to export a "@" character in the template in the code or static content. For example, I used the "@" character in the email address in the following example:

When parsing a file, Razor analyzes the content on the right of the "@" character to determine whether it is code (if it is a cshtml file, it is C # code, if it is a vbhtml file, it is the VB Code) or static text content. The code in the above example will output the following HTML (the email address is output as static content, while @ datetime. Now is executed as code ):

If you encounter content in the same format as the Code (or you want to treat the Code as the content), you can explicitly Press @ to escape it with another "@" character.

Identify embedded content

When HTML text is embedded in an IF/else, foreach, or other BLOCK statement, you can use an HTML or xml tag to enclose the nested content, in this way, you can better understand the beginning of a text content block.

For example, in the following example, I use the <span> label to enclose multiple lines of text content, and the text contains a code block:

The result displayed on the client is as follows-note the <span> label:

If you do not want to output External labels to the client when displaying text content, you can use <text> to enclose the nested content:

The output result of the above Code on the client is as follows-note that the <text> label is not output:

HTML Encoding

By default, the content generated by the "@" Statement block will automatically filter and convert HTML code to [yimin1] to better prevent XSS attacks.

Layout Design/master page-Basics

It is important to maintain a consistent page view style on the site. ASP. NET 2.0 introduces the concept of "master page" to help implement this function when using a. aspx-based page or template. Razor also supports this concept. It uses layout pages. You can first define a general site template, then, inherit the unified view defined by the template from other site views or pages.

A simple example of layout design

The following is an example of a simple layout design page. The file will be saved as "sitelayout. cshtml ". It contains all static HTML text content and dynamic server-side code to be placed in the page. Next, we added an auxiliary function named "renderbody ()", which is placed in the template where the specific content needs to be "filled" based on the requested URL:

Next we will create another name named "home. cshtml "view template, which only contains the necessary text content and code to form the specific content of the requested page, the peripheral content is provided by the layout template:

Pay attention to how we explicitly set the "layoutpage" attribute in the home. cshtml file. It specifies the layout design template that we expect to use sitelayout. cshtml as the view. We can also. net MVC controller (Controller) calls home. when you use the cshtml view template, you can specify the layout design file or configure it as the default layout design template of the site (in this case, we only need to specify it in a file in the project, and all view templates will automatically use it ).

When we display home. cshtml as a view template, it merges the content of the layout design page and child page, and then sends the following content to the client:

Concise, clear, and expressive code

In the above example, it is worth noting that the layout definition and Their syntax used in views/pages are clear and concise. The sitelayout. cshtml and home. cshtml codes listed above already contain two files.All code-No additional configuration steps or redundant labels, no <% @ Page %> prefix, and no other labels or attributes need to be set.

We try our best to make the written code concise and fluent. We also want anyone to open, edit, and adjust/customize them in a text editing program. No need for code generation or smart prompts (intelliisense ).

Layout Design page/master page-overwrite some content

The layout design page can selectively define several different "sections" and allow the view templates designed based on this layout to overwrite custom content through "filling. This allows you to overwrite nonconsecutive sections on the layout design page in the view to make the layout design more flexible.

For example, we go back to the sitelayout. cshtml file and define two sections in it, so that the view template can selectively fill these two sections. We name the Section as "menu" and "footer"-then in the rendersection () the optional = true parameter passed in by the auxiliary function indicates that they are optional padding segments (we can use the latest optional parameter Syntax of C # To Do This, I also mentioned this usage in my previous blog ).

Because the two sections are marked as "optional", they do not need to be defined in the home. cshtml file. Even if you don't have them, the site can still work normally.

Let's go back to home. cshtml and customize the menu and footer sections. The following section contains home. cshtmlAll-No more content. Note: I have set layoutpage as the default template for the site range-so it is not displayed in it.

The "menu" and "footer" sections we override are defined in the @ section {} block named after the corresponding name in the file. We deliberately do not require you to include "Main/body" content in the section, instead, inline them in the page (except to save the number of keyboard hits, after adding a new section on the layout design page, you do not need to modify the syntax of all existing pages ).

When you change home. when cshtml is displayed in the form of a view template, it will now combine the content in the layout design page and child page, and integrate the content overwritten by the two custom sections, the final content sent to the client is as follows:

Encapsulate and reuse HTML auxiliary functions

We just talked about how to use the layout design page to provide a unified view for the site. Now let's take a look at how to encapsulate the HTML generation function into a function library by creating reusable "HTML auxiliary functions", so that the function can be reused on the entire site-or even on multiple sites.

Code-based HTML auxiliary functions

ASP. net mvc has an "HTML helper function" concept-encapsulates the HTML generation logic and functions that can be used in code blocks. Currently, they are implemented purely by code, and generally by extension method. All existing HTML extension functions built in ASP. net mvc can be used in the "Razor" view engine (no code needs to be modified ):

Declarative HTML auxiliary functions

Using Code-only classes to generate HTML can work-but not ideal.

Let's take a look at another feature of razor, using simple and more descriptive methods to create reusable HTML helper functions. We plan to allow you to create reusable auxiliary functions using the @ helper {} declarative syntax similar to the following:

You will be able to put the. cshtml file containing this helper function in a folder of views \ helpers, and then you can use them on the site (no other steps ):

In the preceding example, we can define parameters for the productlisting () function. In this way, you can pass in any parameters for the function (and you can also fully utilize the features of optional parameters, nullable type, model, and other existing programming languages ), in addition, Visual Studio provides powerful debugging support.

Note: The @ helper syntax is not available in razor's first beta version-but we hope to include it in the next release. Code-based helper functions can be used in the first beta version.

Input inline template as parameter

Another useful (or fairly good) function in razor is to allow the "inline template" parameter to be passed into the Helper function. These "inline templates" can contain HTML and code at the same time, and can be called by auxiliary functions as a line.

In the following example, the "Grid" HTML helper function presents a DataGrid on the client through this technology:

In the preceding example, the grid. Render () function calls the C # syntax. The new syntax-C # named parameter is used to pass a strongly typed parameter to the grid. Render function. This also means that we can use all the smart prompts and the syntax check function during compilation.

When defining a column, the parameter "format" is passed to an "inline template", which also contains custom HTML and code. They are displayed in a way that uses custom data. What's more, the grid auxiliary function can call our "inline template" as a delegate. It can be called as soon as it is called and as many times as it is called. In the above scenario, each line of the grid is displayed, it will be called once-and the "item" variable is passed in so that our template can display the appropriate content.

This feature allows you to develop more powerful HTML auxiliary functions. In the future, you can either use code (the same as creating an extension function), or use the declarative @ helper {} method to compile HTML helper functions.

Support for Visual Studio

As mentioned above, one of Razor's goals is to minimize the number of keyboard hits and use a common text editor to write (notepad is good ). We can achieve this goal by ensuring that the syntax is clear, simple, and competent.

Visual Studio also supports razor, which makes you feel richer when writing razor code in it. For razor-based source files, we provide the complete HTML, JavaScript, and C #/VB Code smart prompt functions:

Note that we even enabled smart prompts for the "@ P." of the product object embedded in the <li> element in the foreach loop body. Note that the. aspx and. cshtml view templates are stored in the \ view folder of Solution Explorer. You can use multiple view engines in a single program-so that you can select the engine that best suits you.

Summary

We think "Razor" is a very good new view engine, which provides a fluent template solution focusing on code. Its coding workflow is fast, expressive, and interesting. The syntax is concise, saves the number of buttons, and increases the readability of the Code. It will be used as a built-in view engine and released with the next version of ASP. net mvc. You can also put the separate. cshtml/. vbhtml in the program and execute them as independent pages-so that you can also use it in the ASP. netweb form program.

In the past few months, developers who have tried it have made great comments on it. We are about to release its first beta version, and we look forward to receiving your feedback on it.

I hope this will help you.

Scott

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.