Lỗi only one model statement is allowed in a file năm 2024
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. Show
Razor syntax reference for ASP.NET Core
In this articleBy Rick Anderson, Taylor Mullen, and Dan Vicarel Razor is a markup syntax for embedding .NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a
2 file extension. Razor is also found in Razor component files (
3). Razor syntax is similar to the templating engines of various JavaScript single-page application (SPA) frameworks, such as Angular, React, VueJs, and Svelte. For more information see, The features described in this article are obsolete as of ASP.NET Core 3.0. Introduction to ASP.NET Web Programming Using the Razor Syntax provides many samples of programming with Razor syntax. Although the topic was written for ASP.NET rather than ASP.NET Core, most of the samples apply to ASP.NET Core. Rendering HTMLThe default Razor language is HTML. Rendering HTML from Razor markup is no different than rendering HTML from an HTML file. HTML markup in
2 Razor files is rendered by the server unchanged. Razor syntaxRazor supports C# and uses the
5 symbol to transition from HTML to C#. Razor evaluates C# expressions and renders them in the HTML output. When an
5 symbol is followed by a , it transitions into Razor-specific markup. Otherwise, it transitions into plain HTML. To escape an
5 symbol in Razor markup, use a second
5 symbol:
The code is rendered in HTML with a single
5 symbol:
HTML attributes and content containing email addresses don't treat the
5 symbol as a transition character. The email addresses in the following example are untouched by Razor parsing:
Scalable Vector Graphics (SVG)SVG foreignObject elements are supported:
Implicit Razor expressionsImplicit Razor expressions start with
5 followed by C# code:
With the exception of the C#
2 keyword, implicit expressions must not contain spaces. If the C# statement has a clear ending, spaces can be intermingled:
Implicit expressions cannot contain C# generics, as the characters inside the brackets (
The preceding code generates a compiler error similar to one of the following:
Generic method calls must be wrapped in an or a . Explicit Razor expressionsExplicit Razor expressions consist of an
5 symbol with balanced parenthesis. To render last week's time, the following Razor markup is used:
Any content within the
5 parenthesis is evaluated and rendered to the output. Implicit expressions, described in the previous section, generally can't contain spaces. In the following code, one week isn't subtracted from the current time:
The code renders the following HTML:
Explicit expressions can be used to concatenate text with an expression result:
0 Without the explicit expression,
6 is treated as an email address, and
6 is rendered. When written as an explicit expression,
8 is rendered. Explicit expressions can be used to render output from generic methods in
2 files. The following markup shows how to correct the error shown earlier caused by the brackets of a C# generic. The code is written as an explicit expression:
1 Expression encodingC# expressions that evaluate to a string are HTML encoded. C# expressions that evaluate to
00 are rendered directly through
01. C# expressions that don't evaluate to
00 are converted to a string by
03 and encoded before they're rendered.
2 The preceding code renders the following HTML:
3 The HTML is shown in the browser as plain text: Hello World
04 output isn't encoded but rendered as HTML markup. Warning Using
04 on unsanitized user input is a security risk. User input might contain malicious JavaScript or other exploits. Sanitizing user input is difficult. Avoid using
04 with user input.
4 The code renders the following HTML:
5 Razor code blocksRazor code blocks start with
5 and are enclosed by
08. Unlike expressions, C# code inside code blocks isn't rendered. Code blocks and expressions in a view share the same scope and are defined in order:
6 The code renders the following HTML:
7 In code blocks, declare local functions with markup to serve as templating methods:
8 The code renders the following HTML:
9 Implicit transitionsThe default language in a code block is C#, but the Razor Page can transition back to HTML:
0 Explicit delimited transitionTo define a subsection of a code block that should render HTML, surround the characters for rendering with the Razor
09 tag:
1 Use this approach to render HTML that isn't surrounded by an HTML tag. Without an HTML or Razor tag, a Razor runtime error occurs. The
09 tag is useful to control whitespace when rendering content:
Explicit line transitionTo render the rest of an entire line as HTML inside a code block, use
13 syntax:
2 Without the
13 in the code, a Razor runtime error is generated. Extra
5 characters in a Razor file can cause compiler errors at statements later in the block. These extra
5 compiler errors:
Conditional attribute renderingRazor automatically omits attributes that aren't needed. If the value passed in is
17 or
18, the attribute isn't rendered. For example, consider the following razor:
3 The preceding Razor markup generates the following HTML:
4 Control structuresControl structures are an extension of code blocks. All aspects of code blocks (transitioning to markup, inline C#) also apply to the following structures: Conditionals
19
20 controls when code runs:
5
21 and
22 don't require the
5 symbol:
6 The following markup shows how to use a switch statement:
7 Looping
24 Templated HTML can be rendered with looping control statements. To render a list of people:
8 The following looping statements are supported:
25
9
26
0
27
1
28
2 Compound
29 In C#, a
30 statement is used to ensure an object is disposed. In Razor, the same mechanism is used to create HTML Helpers that contain additional content. In the following code, HTML Helpers render a
31 tag with the
29 statement:
3
33 Exception handling is similar to C#:
4
34 Razor has the capability to protect critical sections with lock statements:
5 CommentsRazor supports C# and HTML comments:
6 The code renders the following HTML:
7 Razor comments are removed by the server before the webpage is rendered. Razor uses
35 to delimit comments. The following code is commented out, so the server doesn't render any markup:
8 DirectivesRazor directives are represented by implicit expressions with reserved keywords following the
5 symbol. A directive typically changes the way a view is compiled or functions. Understanding how Razor generates code for a view makes it easier to understand how directives work.
9 The code generates a class similar to the following:
0 Later in this article, the section explains how to view this generated class.
37 The
37 directive adds the given attribute to the class of the generated page or view. The following example adds the
39 attribute:
1 The
37 directive can also be used to supply a constant-based route template in a Razor component. In the following example, the
41 directive in a component is replaced with the
37 directive and the constant-based route template in
43, which is set elsewhere in the app to "
44":
2
45 This scenario only applies to Razor components (
3). The
45 block enables a Razor component to add C# members (fields, properties, and methods) to a component:
3 For Razor components,
45 is an alias of and recommended over
49. More than one
45 block is permissible.
49 The
49 directive enables adding C# members (fields, properties, and methods) to the generated class:
4 In Razor components, use
45 over
49 to add C# members. For example:
5 The code generates the following HTML markup:
6 The following code is the generated Razor C# class:
7
49 methods serve as templating methods when they have markup:
8 The code renders the following HTML:
9
57 The
57 directive implements an interface for the generated class. The following example implements System.IDisposable so that the Dispose method can be called:
0
59 The
59 directive provides full control of the class the view inherits:
1 The following code is a custom Razor page type:
2 The
61 is displayed in a view:
3 The code renders the following HTML:
4
62 and
59 can be used in the same view.
59 can be in a
65 file that the view imports:
5 The following code is an example of a strongly-typed view:
6 If "[email protected]" is passed in the model, the view generates the following HTML markup:
7
66 The
66 directive enables the Razor Page to inject a service from the service container into a view. For more information, see Dependency injection into views.
68 This scenario only applies to Razor components (
3). The
68 directive specifies a layout for routable Razor components that have an directive. Layout components are used to avoid code duplication and inconsistency. For more information, see ASP.NET Core Blazor layouts.
62 This scenario only applies to MVC views and Razor Pages (
2). The
62 directive specifies the type of the model passed to a view or page:
8 In an ASP.NET Core MVC or Razor Pages app created with individual user accounts,
75 contains the following model declaration:
9 The class generated inherits from
76:
0 Razor exposes a
77 property for accessing the model passed to the view:
1 The
62 directive specifies the type of the
77 property. The directive specifies the
80 in
81 that the generated class that the view derives from. If the
62 directive isn't specified, the
77 property is of type
84. For more information, see .
85 The
85 directive:
2 For the Razor Pages example shown in the following table:
93
92
95
96
97
98 The preceding relationships apply to import files used with MVC views and Razor components. When multiple import files have a
85 directive, the file closest to the page, view, or component in the directory tree is used to set the root namespace. If the
00 folder in the preceding example has an imports file with
01 (or the
97 file contains
01), the result is shown in the following table. Page Namespace
93
92
95
96
97
09
41 The
41 directive has different effects depending on the type of the file where it appears. The directive:
13 This scenario only applies to Razor components (
3). When set to
18 (default), whitespace in the rendered markup from Razor components (
20 This scenario only applies to Razor components (
3). Sets the render mode of a Razor component:
For a component instance:
3 In the component definition:
4 Note Blazor templates include a static
30 directive for RenderMode in the app's
26 file (
20 syntax:
5 Without the preceding directive, components must specify the static RenderMode class in
20 syntax explicitly:
6 For more information, including guidance on disabling prerendering with the directive/directive attribute, see ASP.NET Core Blazor render modes.
30 This scenario only applies to MVC views and Razor Pages (
2). The
30 directive is used in conjunction with MVC and Razor Pages layouts to enable views or pages to render content in different parts of the HTML page. For more information, see Layout in ASP.NET Core.
33 This scenario only applies to Razor components (
3). The
33 directive declares a generic type parameter for the generated component class:
7 Generic types with
36 type constraints are supported:
8 For more information, see the following articles:
29 The
29 directive adds the C#
30 directive to the generated view:
9 In Razor components,
29 also controls which components are in scope. Directive attributesRazor directive attributes are represented by implicit expressions with reserved keywords following the
5 symbol. A directive attribute typically changes the way an element is compiled or functions.
42 This scenario only applies to Razor components (
3).
42 allows a component to render non-declared attributes. For more information, see ASP.NET Core Blazor attribute splatting and arbitrary parameters.
45 This scenario only applies to Razor components (
3). Data binding in components is accomplished with the
45 attribute. For more information, see ASP.NET Core Blazor data binding.
48 This scenario only applies to Razor components (
3). Use the
48 attribute with the attribute to provide a System.Globalization.CultureInfo for parsing and formatting a value. For more information, see .
52 This scenario only applies to Razor components (
3).
52 assigns a form name to a Razor component's plain HTML form or a form based on EditForm (). The value of
52 should be unique, which prevents form collisions in the following situations:
For more information and examples, see ASP.NET Core Blazor forms overview.
57 This scenario only applies to Razor components (
3). Razor provides event handling features for components. For more information, see ASP.NET Core Blazor event handling.
59 This scenario only applies to Razor components (
3). Prevents the default action for the event.
61 This scenario only applies to Razor components (
3). Stops event propagation for the event.
63 This scenario only applies to Razor components (
3). The
63 directive attribute causes the components diffing algorithm to guarantee preservation of elements or components based on the key's value. For more information, see Retain element, component, and model relationships in ASP.NET Core Blazor.
66 This scenario only applies to Razor components (
3). Component references (
Templated Razor delegatesThis scenario only applies to MVC views and Razor Pages (
2). Razor templates allow you to define a UI snippet with the following format:
0 The following example illustrates how to specify a templated Razor delegate as a Func 70 that has a
71 property.
1
2 The template is rendered with
72 supplied by a
73 statement:
3 Rendered output:
4 You can also supply an inline Razor template as an argument to a method. In the following example, the
74 method receives a Razor template. The method uses the template to produce HTML content with repeats of items supplied from a list:
5 Using the list of pets from the prior example, the
74 method is called with:
6 Rendered output:
7 Tag HelpersThis scenario only applies to MVC views and Razor Pages (
2). There are three directives that pertain to Tag Helpers. Directive Function Makes Tag Helpers available to a view. Removes Tag Helpers previously added from a view. Specifies a tag prefix to enable Tag Helper support and to make Tag Helper usage explicit. Razor reserved keywordsRazor keywords
Razor keywords are escaped with
88 (for example,
89). C# Razor keywords
C# Razor keywords must be double-escaped with
04 (for example,
05). The first
5 escapes the Razor parser. The second
5 escapes the C# parser. Reserved keywords not used by Razor
Inspect the Razor C# class generated for a viewThe Razor SDK handles compilation of Razor files. By default, the generated code files aren't emitted. To enable emitting the code files, set the
09 directive in the project file (
11:
8 When building a 6.0 project (
13 build configuration, the Razor SDK generates an
14 directory in the project root. Its subdirectory contains the emitted Razor page code files. The Razor SDK handles compilation of Razor files. When building a project, the Razor SDK generates an
15 directory in the project root. The directory structure within the
16 directory mirrors the project's directory structure. Consider the following directory structure in an ASP.NET Core Razor Pages 2.1 project:
9 Building the project in
13 configuration yields the following
18 directory:
0 To view the generated class for
93, open
20. View lookups and case sensitivityThe Razor view engine performs case-sensitive lookups for views. However, the actual lookup is determined by the underlying file system:
Developers are encouraged to match the casing of file and directory names to the casing of:
Matching case ensures the deployments find their views regardless of the underlying file system. Imports used by RazorThe following imports are generated by the ASP.NET Core web templates to support Razor Files:
1 Additional resourcesIntroduction to ASP.NET Web Programming Using the Razor Syntax provides many samples of programming with Razor syntax. Collaborate with us on GitHub The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide. |