ASP. Fourth-MVC (3.2) Razor syntax reference

Source: Internet
Author: User
Tags button type html comment

Original: Razor Syntax Reference
Taylor Mullen, Rick Anderson
Translation: Liu Yi (alexlewis)
Proofreading: He Shiodome

What is Razor?

Razor is a markup syntax that can be converted to a Web page based on server-side code. The Razor syntax consists of Razor tags, C #, and HTML. Files that contain Razor are usually named . cshtml .

Render HTML

The default language for Razor is HTML. There is no difference between rendering from Razor to HTML and directly an HTML file, this Razor file contains the following markup:

<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 @ switches from HTML to C # by using symbols. Razor arithmetic C # expressions and renders them as HTML output. Razor can be switched from HTML to C # by Razor the specified tag. When the symbol is followed by @ a Razor reserved word, it will switch to Razor specific tag, otherwise switch to normal C #.

HTML If you need to include @ symbols, you need to use two @@ symbols to escape, such as:

<p>@@Username</p>

This renders the following HTML:

 <p>@Username</p>

This will not cause the message address to be @ processed as a converted character (and then switch to the Razor specified tag or C # mode) because it is included in the HTML attribute or content.
<a href="mailto:[email protected]">[email protected]</a>

An implicit Razor expression

An implicit Razor expression is represented by @ a symbol, followed by C # code, such as:

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

An await implicit expression other than the C # keyword cannot contain spaces. For example, you can infiltrate some spaces in a C # statement, as long as the C # statement ends explicitly:

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

An explicit Razor expression contains a pair of parentheses @ , such as when the last week was rendered on the page:

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

Any @() content that is inside will be calculated and rendered out.
Implicit expressions usually cannot contain spaces, such as the following code, and last week's time cannot be obtained by subtracting the current time:

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

This will be rendered as:

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

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

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

If you write <p>[email protected]</p> this non-explicit expression, it will be treated as an e-mail address and rendered as <p>[email protected]</p> . When it is written as an explicit expression, it is rendered as a <p>Age33</p> .

Expression encoding

A C # expression evaluates to a string that is HTML-encoded. The C # expression evaluates to Ihtmlcontent and will be rendered directly IHtmlContent.WriteTo to the page. IHtmlContentC # Expressions that are not evaluated will be converted to strings (through ToString ) and encoded before rendering. Let's say the following Razor tag:

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

Will render as this piece of HTML:

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

and the browser will appear as:

<span>Hello World</span>

HtmlHelper Raw output will not be encoded but will be rendered as HTML markup.

Warning
There is a security risk for unauthorized user input HtmlHelper.Raw . User input may contain malicious JavaScript code or other attacks. It is very difficult to filter and clean up the information entered by the user, so try to avoid using it for user input HtmlHelper.Raw .

The following Razor mark:

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

Will render as:

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

Razor blocks of code are used to enclose @ {} them. Unlike expressions, C # code within a block of code is not rendered to the page. The code blocks and expressions in the Razor page share the same scope and are defined sequentially (that is, the objects previously declared in the code block can be used in subsequent blocks of code and expressions).

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

Will render as:

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

The default language for code blocks is C #, but you can switch to HTML at any time. HTML within a block of code can be rendered correctly.

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

In order to define a sub-region of the rendered HTML in a code block, surround it with Razor tags around the characters that need to be rendered <text> :

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

Try this approach when you need 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 fail at run time.

To @:Symbolic explicit row conversions

In order to embed HTML into a code block (so that it can be rendered), you can use the @: 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 fail at run time.

Control structure

The control structure (controller structures) is a code block expression. All types of code blocks, including transition tags, inline C #, apply the following structure:

@ifelse ifelseAnd @switchConditions

When @if a specified condition is met, the @if series keyword gets control and runs the code in if:

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

elseAnd else if does not necessarily require @ symbols:

@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, just like this:

@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 whileCycle

You can use the loop control statement to render the formatted HTML, such as the Person 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);
@usingComposite

The using statement is used in C # to ensure that the object is disposed correctly. This same mechanism in Razor is used to create HTML helpers that contain additional content. For example, we can use HTML helpers to @using render a form tag through a statement:

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

You can also perform some actions like the above with Tag Helpers at the action level.

@trycatchAnd 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 protect important code with the lock statement:

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

Razor supports C # and HTML annotations. For example, the following markup:

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

Rendered by the server as:

<!-- HTML comment -->

Razor comments will be removed by the server before the page is rendered. Razor use @* *@ to define annotations. The following code is commented out, so the server does not render any markup:

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

The Razor directive behaves as an @ implicit expression of "symbol + reserved keyword". Directives can often change the parsing of pages or enable different functions for Razor pages.
Understanding how Razor generates code for a view makes it easy to understand how the instructions 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 similar to 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 that views the build view explains how to view this automatically generated class.

@using

@usingDirective will add C # directives to the Razor page using .

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

@modelThe directive allows you to specify a type for the model passed into the Razor page with the following syntax:

@model TypeNameOfModel

For example, if you create an ASP. NET Core MVC application with authentication, you can see the following model declaration in the views/account/login.cshtml Razor View File:

@model LoginViewModel

In the instruction sample class, an automatically generated class inherits from RazorPage<dynamic> . By adding @model , you can control what you inherit, such as:

@model LoginViewModel

The following class will be generated

public class _Views_Account_Login_cshtml : RazorPage<LoginViewModel>

The Razor page exposes a Model property to the model access for the incoming page.

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

@modelThe directive can specify a type for this property (by specifying the type in the automatically generated class RazorPage<T> T ). If you do not specify @model an instruction, then Model the property will use the type dynamic . The value of the model is passed into the view from the controller. See strongly typed models and the @model keyword for more information.

@inherits

@inheritsdirectives give you complete control over the classes inherited by the Razor page:

@inherits TypeNameOfClassToInheritFrom

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

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

The Razor will then be generated <div>Custom text: Hello World</div> .

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

You cannot use and at the same time on the same page @model @inherits . You can use directives in the *_viewimports.cshtml* file @inherits and then import them in the other Razor pages. For example, if your Razor view imports the following *_viewimports.cshtml* file:

@inherits CustomRazorPage<TModel>

So in the following strongly typed Razor file

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

This will generate an HTML tag:

<div>The Login Email: [email protected]</div><div>Custom text: Hello World</div>

"[email protected]" was passed in the model.

For more information, see Layout view

@inject

@injectThe instructions allow you to inject services from the service container on the Razor page, and see injecting services into view for more information.

@functions

@functionsDirectives allow you to add function-level content to the Razor page with the following syntax:

@functions { // C# Code }

For example:

@functions {    public string GetHello()    {        return "Hello";    

Generate the following HTML markup:

<div>From method: Hello</div>

The resulting Razor C # resembles the following paragraph:

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

@sectionDirectives are typically used with layout pages, which allows the view to render HTML pages with different content. See Sections for more details.

Taghelpers

Details of the following Tag Helpers instructions can be viewed by clicking on the link.

    • @addTagHelper
    • @removeTagHelper
    • @tagHelperPrefix
Razor reserved keyword Razor keyword
    • Functions
    • Inherits
    • Model
    • Section
    • Helper (ASP. NET Core not supported)

The Razor keyword can be escaped, like @(Razor Keyword) , to cite an example: @(functions) . The above is a complete example.

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

C # Razor keywords need to use two escape symbols, like @(@C# Razor Keyword) , give a practical example: @(@case) . The first @ escape character is used for Razor parsing, and the second @ escape character for C # parsing. The above is a complete example.

Razor reserved Keywords not used
    • Namespace
    • Class

The following are the escapes of all Razor reserved words:

@{//Razor keywords.    var @functions = "Functions";    var @inherits = "Inherits";    var @model = "Model";    var @section = "section";         var @helper = "helper";    Not supported by ASP.    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 for the build 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);    }}

Overwrite the icompilationservice by adding the above class to MVC:

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

On the Compile method CustomCompilationService , set a breakpoint on the view compilationContent .

Back to Catalog

Reference page:hTTP://QINgQINgQuege.CNbLogs.Com/P/5933752.hTmL

ASP. Fourth-MVC (3.2) Razor syntax reference

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.