Describes the "Razor"-asp. NET a new view engine

Source: Internet
Author: User
Tags visual studio 2010

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

All along, ASP. NET MVC supports the concept of a "view engine"-a pluggable module with a template of different syntax. The current ASP. NET MVC "default" View engine is the. aspx/.ascx/.master file template used by ASP. Some of the other popular ASP. NET MVC View engines today include spark and Nhaml.

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

Design goals

In designing and Evaluating "Razor", we keep in mind the following goals:

· Compact, expressive and fluid : Razor Minimizes the number of characters that need to be typed in a file, giving you a refreshing coding experience. Unlike most templates, you don't break the thrill of knocking code because you need to label server-side blocks of code in HTML. The code parser is smart enough to infer from your code whether it is a server-side code. This makes its simple, expressive syntax input clean, fast, and fun.

· Get started : Razor is very easy to get started with, you just need to know a little new stuff to master it, and using your existing programming language and HTML knowledge is enough.

· not a new programming language : We try to avoid creating a new imperative language for Razor. Instead, we want programmers to use the razor only with the existing C#/VB (or other) programming language knowledge, and we just provide a very good markup syntax based on template-generated HTML in your chosen programming language.

· you can write with any text editor : Razor does not require any special tools and can be programmed efficiently using an old-fashioned text editor ("Notepad" is good).

· good smart sense input hint : Although Razor is not designed for a tool or code editor, it still has great smart hints in Visual Studio. We will upgrade Visual Studio 2010 and Visual Web Developer 2010 so that it has the full editor smart hints feature.

· Easy Unit Testing : The new View engine supports unit tests on views, does not require a controller or Web server, and can be included in any unit test project-no separate application domain (App-domain) is required.

Over the past few months, we have been using razor to write programs and have invited some volunteers (including several groups of non-. NET Web programmer) to do usability research. The people who have used it have done a good job of judging it.

Flexible choice of space

Asp. One of the best places to net is that most of the components are pluggable. If you find a component that is not good to use, you can change it at any time.

The next version of ASP. NET MVC will include a new add-and-View dialog box, which allows you to easily select the syntax you want to use when creating a new view template file. It also makes it easy for you to select any view engine installed on the machine-choose the view scheme that you feel most natural:

Razor will be one of the built-in view engines for ASP. All view assist (helper) methods and programming model attributes support both the razor and. aspx view engines.

You will also be able to mix view templates written by multiple view engines in a single site or program. For example, you can write some views, some with an. aspx file, some with a. cshtml or. vbhtml file (respectively, Razor's C # and VB versions of the file suffix), and others with spark or NHAML. You can also include a local view template written in another engine in a view template that takes one view engine. In short, you have a flexible choice of space.

Razor version of "Hello World"

Razor allows you to start with a static HTML page (or any text content) and add server-side code to make it a dynamic page. One of the core design concepts of razor is to make the coding process smoother and to quickly add server-side code to HTML tags with a minimum number of keystrokes.

Let's create a simple example: "Hello World", whose final output looks like this:

Use. ASPX "code fragment [II]" is written in the way

If you use the existing ASP. aspx markup syntax to write the "Hello World" example above, we need to use "<%=%>" in the HTML tag to mark "Code fragment":

Looking closely, you can see that each code fragment in the previous example requires 5 characters ("<%=%>") to indicate where the code begins and ends. And there are a few characters on the keyboard that are not particularly good to knock on (especially the "%" key-it is located on most of the upper middle of the keyboard).

Use razor syntax to write

In razor, you only need to use an "@" character to identify the beginning of the code block, unlike the "<%%>" code fragment, Razor does not require you to explicitly indicate the end of the code block:

The Razor parser understands the syntax of C # or VB used in blocks of code-that's why we don't need to explicitly shut down blocks of code in the previous example. Razor can automatically recognize that the above statements are separate blocks of code and silently close them for us.

Look, even a trivial example like "Hello World" saves us 12 keystrokes. and the "@" character on the keyboard is also easier to press than the "%" character, knocking it faster and smoother.

Looping and inline HTML examples

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

Write with. ASPX "Code Fragment"

If you use the ASP. aspx markup syntax, we may need to write code like the following to dynamically generate a <ul> list that contains the <li> elements that represent each item:

Using the Razor syntax

The following is the code that generates the razor version of the same output:

Notice how the "@" symbol starts a "foreach" loop and embeds a line of HTML statements that contain blocks of code within the loop. Because the razor parser knows the C # syntax that we use in the code block, it recognizes that the contents of the <li> tag should be included in the foreach code block and loop through them. It even knows that the end of the "}" end of the Foreach loop.

Razor is smart enough to recognize the @p in the <li> tag. Name and @p.price are server-side code-and execute them each time the loop is executed. Also note that razor can deduce @p in the case of HTML and code blending. The end position of the name and @p.price code block.

There's no need to add a lot of open/close tags to your template to write code that feels really hearty.

If code block and multiline statement

Here are a few other common scenarios:

If statement

As with the foreach example above, you can embed the content (or other C # or VB language elements) directly in the IF statement without explicitly indicating where the code block starts and ends. For example:

Multi-line statements

You can annotate a multiline statement with the "@{code}" as follows:

Note that in the above example, a variable can be referenced by more than one code block-the variable "message" is defined in a "@{}" block that contains multiple lines of statements, but can also be used by @message blocks of code. This is similar to the syntax for "<%%>" and "<%=%>" in the. aspx file.

Multi-Symbol statement

The "@ ()" syntax allows you to have multiple symbols in a block of code, for example, we can override the code in the "@ ()" code block for connecting strings and numbers in the example above:

Integrating code and Content

The razor parser has built in a lot of language intelligence-dirty work dirty help you do.

In HTML, will it affect the use of the "@" symbol in e-mail addresses and elsewhere?

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

When parsing a file, Razor will parse the right side of the "@" character to determine if it is the code (if it is a cshtml file, that is the C # code, and if it is the vbhtml file that is VB code) or static text content. The code in the example above outputs the following HTML (the mail address is treated as a static content output, and @datetime.now is executed as code):

If you encounter content in the same format as the code (or if you want to view the code as content), you can explicitly hit @@ 来 escape with another "@" character.

Identify the embedded content

When embedding HTML text in a If/else,foreach or other block statement, consider wrapping the nested content with an HTML or XML tag, so that you can more clearly indicate the beginning of a block of text content.

For example, the following example I use the <span> tag to surround multiple lines of text, and there is a block of code in it:

The results displayed on the client are as follows-note the <span> tag:

If you do not want to display the text content, the outside of the label output to the client, you can consider using <text> to enclose nested content:

The above code in the client's output is as follows-please note that the outside <text> tag is not being exported:

HTML encoding

By default, the "@" statement block generates content that automatically filters and transforms HTML code [YIMIN1] to better protect against XSS-breaking scripting attacks.

Layout/master Page Scenarios-Basics

It is important to maintain a consistent page look and feel style in your site. ASP. NET 2.0 introduces the concept of master page, which is used to help implement this functionality when using. aspx-based pages or templates. Razor also supports this concept, which uses "layout pages"-You can define a common site template and then inherit the unified look and feel of the template definition in other views or pages of the site.

A simple example of layout design

Here is an example of a simple layout design page that will be saved as "sitelayout.cshtml". It contains all the static HTML text content and dynamic server-side code to be placed on the page. We then added a helper function called "renderbody ()" Where the template needs to "fill in" the specific content according to the requested URL:

Next we create a view template called "home.cshtml", which contains only the necessary textual content and code to form the specific content of the requested page, and the external content is provided by the layout template:

Notice how we explicitly set the "Layoutpage" property in the Home.cshtml file above. It indicates the layout design template that we expect to use sitelayout.cshtml as the view. We can also specify this layout file or configure it as the default layout template for the site (in which case we only need to specify it in a file in the project) when the ASP. Home.cshtml This view template is called , and all view templates will automatically adopt it).

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

Simple, clear, expressive code

One of the notable places in the above example is the clear and concise syntax for layout definitions and their use in views/pages. The sitelayout.cshtml and home.cshtml codes listed above already contain all the code for two files-no additional configuration steps or redundant tags, no <%@ Page%> prefixes, There is no need to set other tags or attributes.

We try to make the code we write simple and smooth. We also want anyone to be able to open, edit, and adjust/customize them in a text-editing program. No code generation or smart hints (IntelliSense) is required.

Layout design page/master page case-Overwrite part of content

The layout page can optionally define several different "sections" that allow a view template based on this layout to overwrite it with "fill in" the custom content. This allows you to overwrite the discontinuous sections of the layout page in the view so that your site layout is more resilient.

For example, we go back to the sitelayout.cshtml file and define two sections in it, so that the view template can have a selective fill of these two sections. We name the section "menu" and "Footer"-and then the rendersection () helper function passes in the optional=true parameter to indicate that they are optional fill sections (we can do this with the latest C # optional parameter syntax, I also mentioned this usage in the previous blog.)

Because two sections are marked as "optional," they are not required to be defined in the home.cshtml file. Even without them, the site can still work properly.

Let's go back to home.cshtml and customize the menu and footer sections. The following contains all the contents of the home.cshtml-no other content. Note: I have set layoutpage as the default site-wide template-so it is not displayed inside.

The "menu" and "Footer" sections we overwrite are defined in the file in the @section {} block named after the corresponding name. We deliberately do not require you to include "main/body" content in the section, instead of inline them in the page (in addition to saving the number of keystrokes, it is also convenient for you to add a new section on the layout page, you do not need to go back to modify the syntax of all existing pages).

When home.cshtml is displayed again as a view template, it now merges the contents of the layout page and the sub-pages and integrates the two custom sections, which are eventually sent to the client:

Encapsulating and reusing HTML helper functions

We just talked about how to use the layout page to give the site a unified look and feel. Now let's look at how to create reusable "HTML helper functions" that encapsulate the functionality of generating HTML into a library of functions, which can be reused across the site-even at multiple sites.

Code-based HTML helper functions

ASP. NET MVC has an "HTML helper" concept-a function that encapsulates the logic that generates HTML and can be used in blocks of code. They are also currently implemented purely through code, typically through extension functions (Extension Method). All existing HTML extension functions built into ASP. NET MVC can be used in the "Razor" view engine (no need to modify any code):

Declarative HTML-helper functions

Using a pure code class to generate HTML can work-but not ideal.

Let's look at another feature of Razor and create reusable HTML helper functions using a simple and more descriptive method. We plan to allow you to create reusable helper functions using @helper {} Declarative syntax like the following:

You will be able to put the. cshtml files that contain this helper function into a views\helpers folder, and then you can use them on the site (there are no more steps):

Note that in the previous example we can define parameters for the productlisting () function. This allows you to pass in arbitrary parameters for the function (and to take full advantage of the features of existing programming languages, such as optional parameters, nullable types, paradigms, and so on), plus the powerful debugging support of Visual Studio.

Note: The @helper syntax is not yet in the first beta version of razor-but we would like to include it in the next release. Code-based helper functions can be used in the first beta release.

Passing in inline templates as parameters

Another useful (or perhaps pretty good) feature of Razor is the ability to pass in the inline template parameter to the helper function. These "inline templates" can contain both HTML and code, and can be called by helper functions.

The "Grid" HTML helper function in the following example renders a DataGrid on the client through this technique:

The Grid.render () function call in the previous example uses the C # syntax. We used the new syntax-c# named parameters to pass strongly typed arguments to the Grid.render function. This also means that we can use all the smart hints, as well as compile-time syntax checking.

When defining a column, it is an inline template that is passed to the "format" parameter-it contains both custom HTML and code that are used to customize how the data is displayed. What's more, the grid helper function can call our "inline template" as a delegate, when the call is called, how many times to invoke it. In the above scenario, each row that renders a grid is called once-and by passing in the "item" variable so that our template can display the appropriate content.

This feature allows you to develop more powerful HTML helper functions. In the future you can either use the code (just as you would create an extension function now), or you can write an HTML helper function using the declarative @helper {} method.

Support for Visual Studio

As I said earlier, one of the goals of razor is to minimize the number of keystrokes, and to write with a plain text editor (Notepad is great). We achieve this goal by ensuring that the grammar is clear and simple and capable.

Visual Studio also supports Razor, which allows you to feel richer when writing razor code inside. For razor-based source files, we provide the complete HTML, JavaScript, and C#/VB code smart hints feature:

Notice that we even "@p" for the product object embedded in the <li> element inside the Foreach Loop body. Smart hints are enabled. It is also important to note that in the "\view" folder in Solution Explorer, both the. aspx and. cshtml view templates are stored. You can use multiple view engines in a single program-making it easy for you to choose the engine that works best for you.

Summarize

We think "Razor" is a very good new view engine that provides a smooth, code-focused template solution. Its coding workflow is fast, expressive, and interesting. The syntax is concise and saves the number of keystrokes, while also improving the readability of the code. It will be published as a built-in view engine and shipped with the next version of ASP. You can also put separate. Cshtml/.vbhtml into the program and execute them as separate pages-so you can also use it in the Asp.netweb form program.

In the last few months, the developers who have tried it have done a good job of evaluating it. We're about to release the first beta version of it and look forward to receiving your feedback on it.

I hope this will be of some help to you.

"Original address" Introducing "Razor" –a new View engine for ASP.

"Original published date" July, 11:01 PM

Describes the "Razor"-asp. NET a new view engine

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.