ASP. NET Core Chinese Document Chapter 4 MVC (3.2) Razor syntax reference, mvcrazor

Source: Internet
Author: User
Tags html comment

ASP. NET Core Chinese Document Chapter 4 MVC (3.2) Razor syntax reference, mvcrazor

Original article: Razor Syntax Reference
By Taylor Mullen and Rick Anderson
Translation: Liu Yi (AlexLEWIS)
Proofreader: He zhenghou

What is Razor?

Razor is a tag syntax that can be converted to web pages based on server code. The Razor syntax consists of the Razor tag, C #, and HTML. Files containing Razor are usually suffixed. Cshtml.

Rendering HTML

The default language of Razor is HTML. There is no difference between rendering as HTML from Razor and directly using an HTML file. Such Razor files contain the following tags:

<p>Hello World</p>

The last page rendered by the server is also<p>Hello World</p>, Without any changes.

Razor syntax

Razor supports C # and uses@Switch the symbol from HTML to C #. Razor calculates the C # expression and renders it as HTML output. Razor can switch from HTML to C # Through the tag specified by Razor #. When@If the symbol is followed by a reserved Razor word, it is switched to a specific Razor mark. Otherwise, it is switched to a common C #.

HTML@Two symbols are required.@@To escape, for example:

<p>@@Username</p>

The following HTML is rendered:

 <p>@Username</p>

In this way, the email address is not included in the HTML feature or content.@To convert characters (then switch to the tag or C # mode specified by Razor ).
<a href="mailto:Support@contoso.com">Support@contoso.com</a>

Implicit Razor expression

The implicit Razor expression starts@Symbol followed by C # code, for example:

<p>@DateTime.Now</p><p>@DateTime.IsLeapYear(2016)</p>

Except C # keywordsawaitAny other implicit expressions cannot contain spaces. For example, you can mix some spaces in the C # statement, as long as the C # statement ends explicitly:

<p>@await DoSomething("hello", "world")</p>
Explicit Razor expression

The explicit Razor expression contains a pair of parentheses.@Symbol, for example, rendering the last week on the page:

<p>Last week this time: @(DateTime.Now - TimeSpan.FromDays(7))</p>

Any@()The content is computed and rendered.
Implicit Expressions generally do not contain spaces. For example, in the following code, the time of last week cannot be obtained by subtracting the current time:

<p>Last week: @DateTime.Now - TimeSpan.FromDays(7)</p>

This will be rendered:

<p>Last week: 7/7/2016 4:39:52 PM - TimeSpan.FromDays(7)</p>

However, you can use an explicit expression to connect the text in the expression result:

@{    var joe = new Person("Joe", 33); }<p>Age@(joe.Age)</p>

If you write<p>Age@joe.Age</p>This non-explicit expression will be processed and rendered as a mail address<p>Age@joe.Age</p>. When an explicit expression is written, it is rendered<p>Age33</p>.

Expression Encoding

C # The string calculated by the expression is HTML encoded. C # The expression is calculated as IHtmlContent, andIHtmlContent.WriteToRendering to the page. Not calculatedIHtmlContentThe C # expressionToString) And encode it before rendering. For example, the following Razor mark:

@("<span>Hello World</span>")

Render the HTML file as follows:

&lt;span&gt;Hello World&lt;/span&gt;

The browser will display:

<span>Hello World</span>

HtmlHelper RawThe output is not encoded but rendered as HTML.

Warning
For unauthorized user inputHtmlHelper.RawThere are security risks. User input may contain malicious JavaScript code or other attacks. It is very difficult to filter and clear user input information.HtmlHelper.Raw.

The following Razor mark:

@Html.Raw("<span>Hello World</span>")

Rendering:

<span>Hello World</span>
Razor code block

The Razor code block starts@And{}Surrounded. Unlike expressions, the C # code in the code block is not rendered to the page. Code blocks and expressions on the Razor page share the same scope and are defined in order (that is, objects previously declared in the code block can be used in subsequent code blocks and expressions ).

@{    var output = "Hello World";}<p>The rendered result: @output</p>

Rendering:

<p>The rendered result: Hello World</p>
Implicit conversion

The default language of the code block is C #, but you can switch to HTML at any time. The HTML in the code block can be correctly rendered.

@{    var inCSharp = true;    <p>Now in HTML, was in C# @inCSharp</p>}
Explicit separation Conversion

To define the HTML sub-areas that can be rendered in the code block, Razor should be used around the characters to be rendered.<text>Tag surround:

@for (var i = 0; i < people.Length; i++){    var person = people[i];    <text>Name: @person.Name</text>}

You can try this method to render HTML content that does not contain HTML tags. However, if neither the HTML Tag nor the Razor tag is included, your Razor page will encounter an error at runtime.

To @:Symbol explicit line Conversion

You can use@:Syntax:

@for (var i = 0; i < people.Length; i++){    var person = people[i];    @:Name: @person.Name}

If the above Code is not used@:, Your Razor page will have an error at runtime.

Control Structure

The controller ures is a code block expression. The following structure applies to all types of code blocks (including transition labels and inline C:

@if, else if, elseAnd @switchCondition

When@ifWhen the specified conditions are met,@ifThe series keywords will get control and run the code in if:

@if (value % 2 == 0){    <p>The value was even</p>}

elseAndelse ifNot necessarily required@Symbol:

@if (value % 2 == 0){    <p>The value was even</p>}else if (value >= 1337){    <p>The value is large.</p>}else{    <p>The value was not large and is odd.</p>}

You can use the switch statement as follows:

@switch (value){    case 1:        <p>The value is 1!</p>        break;    case 1337:        <p>Your number is 1337!</p>        break;    default:        <p>Your number was not 1 or 1337.</p>        break;}
@for, @foreach, @whileAnd @do whileLoop

You can use the loop control statement to render the HTML that has been formatted, such as the human name table:

@{    var people = new Person[]    {          new Person("John", 33),          new Person("Doe", 41),    };}

You can use any of the following loop statements:

@for

@for (var i = 0; i < people.Length; i++){    var person = people[i];    <p>Name: @person.Name</p>    <p>Age: @person.Age</p>}

@foreach

@foreach (var person in people){    <p>Name: @person.Name</p>    <p>Age: @person.Age</p>}

@while

@{ var i = 0; }@while (i < people.Length){    var person = people[i];    <p>Name: @person.Name</p>    <p>Age: @person.Age</p>    i++;}

@do while

@{ var i = 0; }@do{    var person = people[i];    <p>Name: @person.Name</p>    <p>Age: @person.Age</p>    i++;} while (i < people.Length);
@usingCompound

The using statement in C # is used to ensure that the object is correctly released. In Razor, this same mechanism is used to create HTML helpers containing additional content. For example, we can use HTML helpers@usingStatement rendering form labels:

@using (Html.BeginForm()){    <div>        email:        <input type="email" id="Email" name="Email" value="" />        <button type="submit"> Register </button>    </div>}

You can also perform operations with Tag Helpers similar to the above at the role level.

@try, catchAnd finally

Exception Handling is very similar to C:

@try{    throw new InvalidOperationException("You did something invalid.");}catch (Exception ex){    <p>The exception message: @ex.Message</p>}finally{    <p>The finally statement.</p>}
@lock

Razor can use lock statements to protect important code:

@lock (SomeLock){    // Do critical section work}
Note

Razor supports C # And HTML annotations. For example, the following mark:

@{    /* C# comment. */    // Another C# comment.}<!-- HTML comment -->

Rendered by the server:

<!-- HTML comment -->

Razor comments will be removed by the server before page rendering. Use Razor@* *@To define annotations. The following code is commented out, so the server will not render any mark:

 @* @{     /* C# comment. */     // Another C# comment. } <!-- HTML comment -->*@
Command

The Razor command displays 「@The implicit expression of symbol + reserved keyword. Commands can change page resolution or enable different functions for Razor pages.
After understanding how Razor generates code for a view, you can easily understand how commands work. The Razor page is used to create a C # file, such as a Razor page:

@{    var output = "Hello World";}<div>Output: @output</div>

A class like the following will be generated:

public class _Views_Something_cshtml : RazorPage<dynamic>{    public override async Task ExecuteAsync()    {        var output = "Hello World";        WriteLiteral("/r/n<div>Output: ");        Write(output);        WriteLiteral("</div>");    }}

The Razor C # class for viewing the generated view explains how to view the automatically generated class.

@using

@usingThe command adds the C #usingCommand.

@using System.IO@{    var dir = Directory.GetCurrentDirectory();}<p>@dir</p>
@model

@modelThe command allows you to specify a type for the model that is passed into the Razor page. Its syntax is:

@model TypeNameOfModel

For example, if you create an ASP. NET Core MVC application with authentication, you canViews/Account/Login. cshtmlThe Razor view file contains the following model declaration:

@model LoginViewModel

In the command sample class, the automatically generated classRazorPage<dynamic>Inheritance. Add@model, You can control what to inherit, such:

@model LoginViewModel

The following class will be generated

public class _Views_Account_Login_cshtml : RazorPage<LoginViewModel>

The Razor page exposesModelAttribute to the model access on the input page.

<div>The Login Email: @Model.Email</div>

@modelThe command can specify a type for this attribute (RazorPage<T>InTType ). If you do not specify@modelCommand, thenModelAttribute will use typedynamic. The model value is passed into the view from the Controller. For more information, see stronugly typed models and the @ model keyword.

@inherits

@inheritsThe command gives you full control over the inherited classes on the Razor page:

@inherits TypeNameOfClassToInheritFrom

For example, let's look at the custom Razor page type below:

using Microsoft.AspNetCore.Mvc.Razor;public abstract class CustomRazorPage<TModel> : RazorPage<TModel>{    public string CustomText { get; } = "Hello World.";}

Then Razor will generate<div>Custom text: Hello World</div>.

@inherits CustomRazorPage<TModel><div>Custom text: @CustomText</div>

You cannot use@modelAnd@inherits. You can use the * _ ViewImports. cshtml * File@inheritsCommand, and then import it on other Razor pages. For example, if your Razor view imports the following * _ ViewImports. cshtml * file:

@inherits CustomRazorPage<TModel>

Then, in the following strong type Razor File

@inherits CustomRazorPage<TModel><div>The Login Email: @Model.Email</div><div>Custom text: @CustomText</div>

This HTML tag will be generated:

<div>The Login Email: Rick@contoso.com</div><div>Custom text: Hello World</div>

The Rick@contoso.com is passed in the model 」.

For more information, see Layout View.

@inject

@injectCommands allow you to inject Services from service containers on the Razor page. For more information, See Injecting Services Into Views.

@functions

@functionsThe command allows you to add function-level content on the Razor page. Its syntax is:

@functions { // C# Code }

For example:

@functions {    public string GetHello()    {        return "Hello";    }}<div>From method: @GetHello()</div> 

Generate the following HTML Tag:

<div>From method: Hello</div>

The generated Razor C # is similar to the following section:

using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc.Razor;public class _Views_Home_Test_cshtml : RazorPage<dynamic>{    // Functions placed between here     public string GetHello()    {        return "Hello";    }    // And here.#pragma warning disable 1998    public override async Task ExecuteAsync()    {        WriteLiteral("\r\n<div>From method: ");        Write(GetHello());        WriteLiteral("</div>\r\n");    }#pragma warning restore 1998
@section

@sectionCommands are usually used with layout pages so that the HTML pages rendered by the view can have different contents. For more information, see Sections.

TagHelpers

For more information about the following Tag Helpers commands, click the link.

  • @ AddTagHelper
  • @ RemoveTagHelper
  • @ TagHelperPrefix
Razor reserved keyword Razor
  • Functions
  • Inherits
  • Model
  • Section
  • Helper (not supported by ASP. NET Core)

The Razor keyword can be escaped, such@(Razor Keyword)For example:@(functions). The above is a complete example.

C # Razor keyword
  • Case
  • Do
  • Default
  • For
  • Foreach
  • If
  • Lock
  • Switch
  • Try
  • Using
  • While

C # The Razor keyword requires two escape characters, such@(@C# Razor Keyword)For example:@(@case). First@Escape Character used for Razor parsing, second@Escape characters are used for C # parsing. The above is a complete example.

Reserved keywords not used by Razor
  • Namespace
  • Class

The following are the escaping of all the reserved Razor characters:

@{    // Razor keywords.    var @functions = "functions";    var @inherits = "inherits";    var @model = "model";    var @section = "section";    var @helper = "helper";         // Not supported by ASP.NET Core.    // C# Razor keywords.    var @case = "case";    var @do = "do";    var @default = "default";    var @for = "for";    var @foreach = "foreach";    var @if = "if";    var @lock = "lock";    var @switch = "switch";    var @try = "try";    var @using = "using";    var @while = "while";    // Reserved keywords not used.    var @namespace = "namespace";    var @class = "class";}<p>Razor keywords.</p><div>@(functions)</div><div>@(inherits)</div><div>@(model)</div><div>@(section)</div><div>@(helper)</div><p>C# Razor keywords.</p><div>@(@case)</div><div>@(@do)</div><div>@(@default)</div><div>@(@for)</div><div>@(@foreach)</div><div>@(@if)</div><div>@(@lock)</div><div>@(@switch)</div><div>@(@try)</div><div>@(@using)</div><div>@(@while)</div><p>Reserved keywords not used</p><div>@(@namespace)</div><div>@(@class)</div>
View the Razor C # class of the generated View

Add the following class to the ASP. NET Core MVC project:

using Microsoft.AspNetCore.Mvc.ApplicationParts;using Microsoft.AspNetCore.Mvc.Razor;using Microsoft.AspNetCore.Mvc.Razor.Compilation;using Microsoft.AspNetCore.Mvc.Razor.Internal;using Microsoft.Extensions.Logging;using Microsoft.Extensions.Options;public class CustomCompilationService : DefaultRoslynCompilationService, ICompilationService{    public CustomCompilationService(ApplicationPartManager partManager,         IOptions<RazorViewEngineOptions> optionsAccessor,         IRazorViewEngineFileProviderAccessor fileProviderAccessor,         ILoggerFactory loggerFactory)         : base(partManager, optionsAccessor, fileProviderAccessor, loggerFactory)    {    }    CompilationResult ICompilationService.Compile(RelativeFileInfo fileInfo,         string compilationContent)    {        return base.Compile(fileInfo, compilationContent);    }}

Add the above class to MVC to overwrite ICompilationService:

public void ConfigureServices(IServiceCollection services){    services.AddMvc();    services.AddSingleton<ICompilationService, CustomCompilationService>();}

InCompileMethodCustomCompilationServiceOn and on The ViewcompilationContent.

Returned directory

Reference page: http://qingqingquege.cnblogs.com/p/5933752.html

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.