diff --git a/aspnetcore/blazor/components.md b/aspnetcore/blazor/components.md index 0f26d4a7ea..7958ad03c4 100644 --- a/aspnetcore/blazor/components.md +++ b/aspnetcore/blazor/components.md @@ -31,9 +31,9 @@ The UI for a component is defined using HTML. Dynamic rendering logic (for examp Members of the component class are defined in an `@code` block. In the `@code` block, component state (properties, fields) is specified with methods for event handling or for defining other component logic. More than one `@code` block is permissible. > [!NOTE] -> In previous versions of ASP.NET Core, `@functions` blocks were used for the same purpose as `@code` blocks. `@functions` blocks continue to work, but we recommend using the `@code` directive. +> In prior previews of ASP.NET Core 3.0, `@functions` blocks were used for the same purpose as `@code` blocks in Razor components. `@functions` blocks continue to function in Razor components, but we recommend using the `@code` block in ASP.NET Core 3.0 Preview 6 or later. -Component members can then be used as part of the component's rendering logic using C# expressions that start with `@`. For example, a C# field is rendered by prefixing `@` to the field name. The following example evaluates and renders: +Component members can be used as part of the component's rendering logic using C# expressions that start with `@`. For example, a C# field is rendered by prefixing `@` to the field name. The following example evaluates and renders: * `_headingFontStyle` to the CSS property value for `font-style`. * `_headingText` to the content of the `

` element. @@ -118,7 +118,7 @@ The following `ParentComponent` can provide content for rendering the `ChildComp ## Attribute splatting and arbitrary parameters -Components can capture and render additional attributes in addition to the component's declared parameters. Additional attributes can be captured in a dictionary and then *splatted* onto an element when the component is rendered using the `@attributes` Razor directive. This scenario is useful when defining a component that produces a markup element that supports a variety of customizations. For example, it can be tedious to define attributes separately for an `` that supports many parameters. +Components can capture and render additional attributes in addition to the component's declared parameters. Additional attributes can be captured in a dictionary and then *splatted* onto an element when the component is rendered using the [@attributes](xref:mvc/views/razor#attributes) Razor directive. This scenario is useful when defining a component that produces a markup element that supports a variety of customizations. For example, it can be tedious to define attributes separately for an `` that supports many parameters. In the following example, the first `` element (`id="useIndividualParams"`) uses individual component parameters, while the second `` element (`id="useAttributesDict"`) uses attribute splatting: @@ -149,9 +149,9 @@ In the following example, the first `` element (`id="useIndividualParams" private Dictionary InputAttributes { get; set; } = new Dictionary() { - { "maxlength", "10" }, - { "placeholder", "Input placeholder text" }, - { "required", "true" }, + { "maxlength", "10" }, + { "placeholder", "Input placeholder text" }, + { "required", "true" }, { "size", "50" } }; } @@ -188,7 +188,7 @@ The `CaptureUnmatchedValues` property on `[Parameter]` allows the parameter to m ## Data binding -Data binding to both components and DOM elements is accomplished with the `@bind` attribute. The following example binds the `_italicsCheck` field to the check box's checked state: +Data binding to both components and DOM elements is accomplished with the [@bind](xref:mvc/views/razor#bind) attribute. The following example binds the `_italicsCheck` field to the check box's checked state: ```cshtml `) is essentially equivalent to the following: ```cshtml - ``` When the component is rendered, the `value` of the input element comes from the `CurrentValue` property. When the user types in the text box, the `onchange` event is fired and the `CurrentValue` property is set to the changed value. In reality, the code generation is a little more complex because `@bind` handles a few cases where type conversions are performed. In principle, `@bind` associates the current value of an expression with a `value` attribute and handles changes using the registered handler. -In addition to handling `onchange` events with `@bind` syntax, a property or field can be bound using other events by specifying an `@bind-value` attribute with an `event` parameter. The following example binds the `CurrentValue` property for the `oninput` event: +In addition to handling `onchange` events with `@bind` syntax, a property or field can be bound using other events by specifying an [@bind-value](xref:mvc/views/razor#bind) attribute with an `event` parameter ([@bind-value:event](xref:mvc/views/razor#bind)). The following example binds the `CurrentValue` property for the `oninput` event: ```cshtml @@ -218,7 +218,7 @@ Unlike `onchange`, which fires when the element loses focus, `oninput` fires whe **Format strings** -Data binding works with format strings. Other format expressions, such as currency or number formats, aren't available at this time. +Data binding works with format strings using [@bind:format](xref:mvc/views/razor#bind). Other format expressions, such as currency or number formats, aren't available at this time. ```cshtml @@ -233,7 +233,7 @@ The `@bind:format` attribute specifies the date format to apply to the `value` o **Component parameters** -Binding also recognizes component parameters, where `@bind-{property}` can bind a property value across components. +Binding recognizes component parameters, where `@bind-{property}` can bind a property value across components. The following child component (`ChildComponent`) has a `Year` component parameter and `YearChanged` callback: @@ -319,7 +319,7 @@ In general, a property can be bound to a corresponding event handler using `@bin ## Event handling -Razor components provide event handling features. For an HTML element attribute named `on` (for example, `onclick` and `onsubmit`) with a delegate-typed value, Razor components treats the attribute's value as an event handler. The attribute's name always starts with `@on`. +Razor components provide event handling features. For an HTML element attribute named `on{event}` (for example, `onclick` and `onsubmit`) with a delegate-typed value, Razor components treats the attribute's value as an event handler. The attribute's name is always formatted [@on{event}](xref:mvc/views/razor#onevent). The following code calls the `UpdateHeading` method when the button is selected in the UI: @@ -366,7 +366,9 @@ In the following example, `UpdateHeading` is called asynchronously when the butt } ``` -For some events, event-specific event argument types are permitted. If access to one of these event types isn't necessary, it isn't required in the method call. +### Event argument types + +For some events, event argument types are permitted. If access to one of these event types isn't necessary, it isn't required in the method call. Supported [UIEventArgs](https://github.com/aspnet/AspNetCore/blob/release/3.0-preview8/src/Components/Components/src/UIEventArgs.cs) are shown in the following table. @@ -385,7 +387,9 @@ Supported [UIEventArgs](https://github.com/aspnet/AspNetCore/blob/release/3.0-pr | Touch | `UITouchEventArgs` – `UITouchPoint` represents a single contact point on a touch-sensitive device. | For information on the properties and event handling behavior of the events in the preceding table, see [EventArgs classes in the reference source](https://github.com/aspnet/AspNetCore/tree/release/3.0-preview8/src/Components/Web/src). - + +### Lambda expressions + Lambda expressions can also be used: ```cshtml @@ -465,7 +469,7 @@ Prefer the strongly typed `EventCallback` over `EventCallback`. `EventCallbac ## Capture references to components -Component references provide a way to reference a component instance so that you can issue commands to that instance, such as `Show` or `Reset`. To capture a component reference, add a `@ref` attribute to the child component and then define a field with the same name and the same type as the child component. +Component references provide a way to reference a component instance so that you can issue commands to that instance, such as `Show` or `Reset`. To capture a component reference, add a [@ref](xref:mvc/views/razor#ref) attribute to the child component and then define a field with the same name and the same type as the child component. ```cshtml @@ -490,7 +494,7 @@ While capturing component references use a similar syntax to [capturing element > [!NOTE] > Do **not** use component references to mutate the state of child components. Instead, use normal declarative parameters to pass data to child components. Use of normal declarative parameters result in child components that rerender at the correct times automatically. -## Use @key to control the preservation of elements and components +## Use \@key to control the preservation of elements and components When rendering a list of elements or components and the elements or components subsequently change, Blazor's diffing algorithm must decide which of the previous elements or components can be retained and how model objects should map to them. Normally, this process is automatic and can be ignored, but there are cases where you may want to control the process. @@ -535,7 +539,7 @@ In some scenarios, use of `@key` minimizes the complexity of rerendering and avo > [!IMPORTANT] > Keys are local to each container element or component. Keys aren't compared globally across the document. -### When to use @key +### When to use \@key Typically, it makes sense to use `@key` whenever a list is rendered (for example, in a `@foreach` block) and a suitable value exists to define the `@key`. @@ -549,13 +553,13 @@ You can also use `@key` to prevent Blazor from preserving an element or componen If `@currentPerson` changes, the `@key` attribute directive forces Blazor to discard the entire `
` and its descendants and rebuild the subtree within the UI with new elements and components. This can be useful if you need to guarantee that no UI state is preserved when `@currentPerson` changes. -### When not to use @key +### When not to use \@key There's a performance cost when diffing with `@key`. The performance cost isn't large, but only specify `@key` if controlling the element or component preservation rules benefit the app. Even if `@key` isn't used, Blazor preserves child element and component instances as much as possible. The only advantage to using `@key` is control over *how* model instances are mapped to the preserved component instances, instead of the diffing algorithm selecting the mapping. -### What values to use for @key +### What values to use for \@key Generally, it makes sense to supply one of the following kinds of value for `@key`: @@ -742,26 +746,7 @@ This is the Index page. > > Partially qualified names aren't supported. For example, adding `@using ComponentsSample` and referencing `NavMenu.razor` with `` isn't supported. -## Razor support - -**Razor directives** - -Razor directives are shown in the following table. - -| Directive | Description | -| --------- | ----------- | -| [\@code](xref:mvc/views/razor#section-5) | Adds a C# code block to a component. `@code` is an alias of `@functions`. `@code` is recommended over `@functions`. More than one `@code` block is permissible. | -| [\@functions](xref:mvc/views/razor#section-5) | Adds a C# code block to a component. Choose `@code` over `@functions` for C# code blocks. | -| `@implements` | Implements an interface for the generated component class. | -| [\@inherits](xref:mvc/views/razor#section-3) | Provides full control of the class that the component inherits. | -| [\@inject](xref:mvc/views/razor#section-4) | Enables service injection from the [service container](xref:fundamentals/dependency-injection). For more information, see [Dependency injection into views](xref:mvc/views/dependency-injection). | -| `@layout` | Specifies a layout component. Layout components are used to avoid code duplication and inconsistency. | -| [\@page](xref:razor-pages/index#razor-pages) | Specifies that the component should handle requests directly. The `@page` directive can be specified with a route and optional parameters. Unlike Razor Pages, the `@page` directive doesn't need to be the first directive at the top of the file. For more information, see [Routing](xref:blazor/routing). | -| [\@using](xref:mvc/views/razor#using) | Adds the C# `using` directive to the generated component class. This also brings all the components defined in that namespace into scope. | -| [\@namespace](xref:mvc/views/razor#section-6) | Sets the namespace of the generated component class. | -| [\@attribute](xref:mvc/views/razor#section-7) | Adds an attribute to the generated component class. | - -**Conditional HTML element attributes** +## Conditional HTML element attributes HTML element attributes are conditionally rendered based on the .NET value. If the value is `false` or `null`, the attribute isn't rendered. If the value is `true`, the attribute is rendered minimized. @@ -788,9 +773,7 @@ If `IsCompleted` is `false`, the check box is rendered as: ``` -**Additional information on Razor** - -For more information on Razor, see the [Razor syntax reference](xref:mvc/views/razor). +For more information, see . ## Raw HTML diff --git a/aspnetcore/blazor/dependency-injection.md b/aspnetcore/blazor/dependency-injection.md index 761b51318a..27ba6fe159 100644 --- a/aspnetcore/blazor/dependency-injection.md +++ b/aspnetcore/blazor/dependency-injection.md @@ -63,7 +63,7 @@ The DI system is based on the DI system in ASP.NET Core. For more information, s ## Request a service in a component -After services are added to the service collection, inject the services into the components using the [\@inject](xref:mvc/views/razor#section-4) Razor directive. `@inject` has two parameters: +After services are added to the service collection, inject the services into the components using the [\@inject](xref:mvc/views/razor#inject) Razor directive. `@inject` has two parameters: * Type – The type of the service to inject. * Property – The name of the property receiving the injected app service. The property doesn't require manual creation. The compiler creates the property. diff --git a/aspnetcore/data/ef-mvc/read-related-data.md b/aspnetcore/data/ef-mvc/read-related-data.md index 2bfe8446ed..5f91e0a645 100644 --- a/aspnetcore/data/ef-mvc/read-related-data.md +++ b/aspnetcore/data/ef-mvc/read-related-data.md @@ -183,7 +183,7 @@ You've made the following changes to the existing code: } ``` -* Added a **Courses** column that displays courses taught by each instructor. See [Explicit Line Transition with `@:`](xref:mvc/views/razor#explicit-line-transition-with-) for more about this razor syntax. +* Added a **Courses** column that displays courses taught by each instructor. For more information, see the [Explicit line transition with @:](xref:mvc/views/razor#explicit-line-transition-with-) section of the Razor syntax article. * Added code that dynamically adds `class="success"` to the `tr` element of the selected instructor. This sets a background color for the selected row using a Bootstrap class. diff --git a/aspnetcore/data/ef-rp/read-related-data.md b/aspnetcore/data/ef-rp/read-related-data.md index a426bf8a35..e37b7ff958 100644 --- a/aspnetcore/data/ef-rp/read-related-data.md +++ b/aspnetcore/data/ef-rp/read-related-data.md @@ -211,7 +211,7 @@ The preceding markup makes the following changes: } ``` -* Added a **Courses** column that displays courses taught by each instructor. See [Explicit Line Transition with `@:`](xref:mvc/views/razor#explicit-line-transition-with-) for more about this razor syntax. +* Added a **Courses** column that displays courses taught by each instructor. See [Explicit line transition with `@:`](xref:mvc/views/razor#explicit-line-transition-with-) for more about this razor syntax. * Added code that dynamically adds `class="success"` to the `tr` element of the selected instructor. This sets a background color for the selected row using a Bootstrap class. diff --git a/aspnetcore/mvc/views/razor.md b/aspnetcore/mvc/views/razor.md index 5890e86c3d..3ca32c42f9 100644 --- a/aspnetcore/mvc/views/razor.md +++ b/aspnetcore/mvc/views/razor.md @@ -3,14 +3,14 @@ title: Razor syntax reference for ASP.NET Core author: rick-anderson description: Learn about Razor markup syntax for embedding server-based code into webpages. ms.author: riande -ms.date: 06/12/2019 +ms.date: 08/05/2019 uid: mvc/views/razor --- # Razor syntax reference for ASP.NET Core By [Rick Anderson](https://twitter.com/RickAndMSFT), [Luke Latham](https://github.com/guardrex), [Taylor Mullen](https://twitter.com/ntaylormullen), and [Dan Vicarel](https://github.com/Rabadash8820) -Razor is a markup syntax for embedding server-based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a *.cshtml* file extension. +Razor is a markup syntax for embedding server-based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a *.cshtml* file extension. Razor is also found in [Razor components](xref:blazor/components) files (*.razor*). ## Rendering HTML @@ -204,7 +204,7 @@ The default language in a code block is C#, but the Razor Page can transition ba ### Explicit delimited transition -To define a subsection of a code block that should render HTML, surround the characters for rendering with the Razor **\** tag: +To define a subsection of a code block that should render HTML, surround the characters for rendering with the Razor `` tag: ```cshtml @for (var i = 0; i < people.Length; i++) @@ -216,12 +216,12 @@ To define a subsection of a code block that should render HTML, surround the cha 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 **\** tag is useful to control whitespace when rendering content: +The `` tag is useful to control whitespace when rendering content: -* Only the content between the **\** tag is rendered. -* No whitespace before or after the **\** tag appears in the HTML output. +* Only the content between the `` tag is rendered. +* No whitespace before or after the `` tag appears in the HTML output. -### Explicit Line Transition with @: +### Explicit line transition with \@: To render the rest of an entire line as HTML inside a code block, use the `@:` syntax: @@ -235,13 +235,13 @@ To render the rest of an entire line as HTML inside a code block, use the `@:` s Without the `@:` in the code, a Razor runtime error is generated. -Warning: Extra `@` characters in a Razor file can cause compiler errors at statements later in the block. These compiler errors can be difficult to understand because the actual error occurs before the reported error. This error is common after combining multiple implicit/explicit expressions into a single code block. +Extra `@` characters in a Razor file can cause compiler errors at statements later in the block. These compiler errors can be difficult to understand because the actual error occurs before the reported error. This error is common after combining multiple implicit/explicit expressions into a single code block. ## Control structures Control structures are an extension of code blocks. All aspects of code blocks (transitioning to markup, inline C#) also apply to the following structures: -### Conditionals @if, else if, else, and @switch +### Conditionals \@if, else if, else, and \@switch `@if` controls when code runs: @@ -286,7 +286,7 @@ The following markup shows how to use a switch statement: } ``` -### Looping @for, @foreach, @while, and @do while +### Looping \@for, \@foreach, \@while, and \@do while Templated HTML can be rendered with looping control statements. To render a list of people: @@ -352,30 +352,27 @@ The following looping statements are supported: } while (i < people.Length); ``` -### Compound @using +### Compound \@using -In C#, a `using` 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 form tag with the `@using` statement: +In C#, a `using` 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 `
` tag with the `@using` statement: ```cshtml @using (Html.BeginForm()) {
- email: - + Email:
} ``` -Scope-level actions can be performed with [Tag Helpers](xref:mvc/views/tag-helpers/intro). - -### @try, catch, finally +### \@try, catch, finally Exception handling is similar to C#: [!code-cshtml[](razor/sample/Views/Home/Contact7.cshtml)] -### @lock +### \@lock Razor has the capability to protect critical sections with lock statements: @@ -442,90 +439,47 @@ public class _Views_Something_cshtml : RazorPage Later in this article, the section [Inspect the Razor C# class generated for a view](#inspect-the-razor-c-class-generated-for-a-view) explains how to view this generated class. - +### \@attribute -### @using - -The `@using` directive adds the C# `using` directive to the generated view: - -[!code-cshtml[](razor/sample/Views/Home/Contact9.cshtml)] - -### @model - -The `@model` directive specifies the type of the model passed to a view: +The `@attribute` directive adds the given attribute to the class of the generated page or view. The following example adds the `[Authorize]` attribute: ```cshtml -@model TypeNameOfModel +@attribute [Authorize] ``` -In an ASP.NET Core MVC app created with individual user accounts, the *Views/Account/Login.cshtml* view contains the following model declaration: +::: moniker range=">= aspnetcore-3.0" + +### \@code + +*This scenario only applies to Razor components (.razor).* + +The `@code` block enables a [Razor component](xref:blazor/components) to add C# members (fields, properties, and methods) to a component: ```cshtml -@model LoginViewModel +@code { + // C# members (fields, properties, and methods) +} ``` -The class generated inherits from `RazorPage`: +For Razor components, `@code` is an alias of [@functions](#functions) and recommended over `@functions`. More than one `@code` block is permissible. -```csharp -public class _Views_Account_Login_cshtml : RazorPage -``` +::: moniker-end -Razor exposes a `Model` property for accessing the model passed to the view: +### \@functions + +The `@functions` directive enables adding C# members (fields, properties, and methods) to the generated class: ```cshtml -
The Login Email: @Model.Email
+@functions { + // C# members (fields, properties, and methods) +} ``` -The `@model` directive specifies the type of this property. The directive specifies the `T` in `RazorPage` that the generated class that the view derives from. If the `@model` directive isn't specified, the `Model` property is of type `dynamic`. The value of the model is passed from the controller to the view. For more information, see [Strongly typed models and the @model keyword](xref:tutorials/first-mvc-app/adding-model#strongly-typed-models-and-the--keyword). +::: moniker range=">= aspnetcore-3.0" -### @inherits +In [Razor components](xref:blazor/components), use `@code` over `@functions` to add C# members. -The `@inherits` directive provides full control of the class the view inherits: - -```cshtml -@inherits TypeNameOfClassToInheritFrom -``` - -The following code is a custom Razor page type: - -[!code-csharp[](razor/sample/Classes/CustomRazorPage.cs)] - -The `CustomText` is displayed in a view: - -[!code-cshtml[](razor/sample/Views/Home/Contact10.cshtml)] - -The code renders the following HTML: - -```html -
Custom text: Gardyloo! - A Scottish warning yelled from a window before dumping a slop bucket on the street below.
-``` - - `@model` and `@inherits` can be used in the same view. `@inherits` can be in a *_ViewImports.cshtml* file that the view imports: - -[!code-cshtml[](razor/sample/Views/_ViewImportsModel.cshtml)] - -The following code is an example of a strongly-typed view: - -[!code-cshtml[](razor/sample/Views/Home/Login1.cshtml)] - -If "rick@contoso.com" is passed in the model, the view generates the following HTML markup: - -```html -
The Login Email: rick@contoso.com
-
Custom text: Gardyloo! - A Scottish warning yelled from a window before dumping a slop bucket on the street below.
-``` - -### @inject - -The `@inject` directive enables the Razor Page to inject a service from the [service container](xref:fundamentals/dependency-injection) into a view. For more information, see [Dependency injection into views](xref:mvc/views/dependency-injection). - -### @functions - -The `@functions` directive enables a Razor Page to add a C# code block to a view: - -```cshtml -@functions { // C# Code } -``` +::: moniker-end For example: @@ -566,38 +520,220 @@ The code renders the following HTML:

Name: Martin Luther King, Jr.

``` -::: moniker-end +### \@implements -### @attribute +The `@implements` directive implements an interface for the generated class. -The `@attribute` directive adds the given attribute to the class of the generated page or view. The following example adds the `[Authorize]` attribute: +The following example implements so that the method can be called: ```cshtml -@attribute [Authorize] +@implements IDisposable + +

Example

+ +@functions { + private bool _isDisposed; + + ... + + public void Dispose() => _isDisposed = true; +} ``` -### @namespace +::: moniker-end -The `@namespace` directive sets the namespace of the class of the generated page or view: +### \@inherits + +The `@inherits` directive provides full control of the class the view inherits: + +```cshtml +@inherits TypeNameOfClassToInheritFrom +``` + +The following code is a custom Razor page type: + +[!code-csharp[](razor/sample/Classes/CustomRazorPage.cs)] + +The `CustomText` is displayed in a view: + +[!code-cshtml[](razor/sample/Views/Home/Contact10.cshtml)] + +The code renders the following HTML: + +```html +
+ Custom text: Gardyloo! - A Scottish warning yelled from a window before dumping + a slop bucket on the street below. +
+``` + + `@model` and `@inherits` can be used in the same view. `@inherits` can be in a *_ViewImports.cshtml* file that the view imports: + +[!code-cshtml[](razor/sample/Views/_ViewImportsModel.cshtml)] + +The following code is an example of a strongly-typed view: + +[!code-cshtml[](razor/sample/Views/Home/Login1.cshtml)] + +If "rick@contoso.com" is passed in the model, the view generates the following HTML markup: + +```html +
The Login Email: rick@contoso.com
+
+ Custom text: Gardyloo! - A Scottish warning yelled from a window before dumping + a slop bucket on the street below. +
+``` + +### \@inject + +The `@inject` directive enables the Razor Page to inject a service from the [service container](xref:fundamentals/dependency-injection) into a view. For more information, see [Dependency injection into views](xref:mvc/views/dependency-injection). + +::: moniker range=">= aspnetcore-3.0" + +### \@layout + +*This scenario only applies to Razor components (.razor).* + +The `@layout` directive specifies a layout for a Razor component. Layout components are used to avoid code duplication and inconsistency. For more information, see . + +::: moniker-end + +### \@model + +*This scenario only applies to MVC views and Razor Pages (.cshtml).* + +The `@model` directive specifies the type of the model passed to a view or page: + +```cshtml +@model TypeNameOfModel +``` + +In an ASP.NET Core MVC or Razor Pages app created with individual user accounts, *Views/Account/Login.cshtml* contains the following model declaration: + +```cshtml +@model LoginViewModel +``` + +The class generated inherits from `RazorPage`: + +```csharp +public class _Views_Account_Login_cshtml : RazorPage +``` + +Razor exposes a `Model` property for accessing the model passed to the view: + +```cshtml +
The Login Email: @Model.Email
+``` + +The `@model` directive specifies the type of the `Model` property. The directive specifies the `T` in `RazorPage` that the generated class that the view derives from. If the `@model` directive isn't specified, the `Model` property is of type `dynamic`. For more information, see [Strongly typed models and the @model keyword](xref:tutorials/first-mvc-app/adding-model#strongly-typed-models-and-the--keyword). + +### \@namespace + +The `@namespace` directive: + +* Sets the namespace of the class of the generated Razor page, MVC view, or Razor component. +* Sets the root derived namespaces of a pages, views, or components classes from the closest imports file in the directory tree, *_ViewImports.cshtml* (views or pages) or *_Imports.razor* (Razor components). ```cshtml @namespace Your.Namespace.Here ``` -If a page or view imports API with an `@namespace` directive, the original file's namespace is set relative to that namespace. +For the Razor Pages example shown in the following table: -If *MyApp/Pages/\_ViewImports.cshtml* contains `@namespace Hello.World`, the namespace of pages or views that import the `Hello.World` namespace is set as shown in the following table. +* Each page imports *Pages/_ViewImports.cshtml*. +* *Pages/_ViewImports.cshtml* contains `@namespace Hello.World`. +* Each page has `Hello.World` as the root of it's namespace. -| Page (or view) | Namespace | -| ---------------------------------- | ----------------------- | -| *MyApp/Pages/Index.cshtml* | `Hello.World` | -| *MyApp/Pages/MorePages/Bar.cshtml* | `Hello.World.MorePages` | +| Page | Namespace | +| ------------------------------------------- | ------------------------------------- | +| *Pages/Index.cshtml* | `Hello.World` | +| *Pages/MorePages/Page.cshtml* | `Hello.World.MorePages` | +| *Pages/MorePages/EvenMorePages/Page.cshtml* | `Hello.World.MorePages.EvenMorePages` | -If multiple import files have the `@namespace` directive, the file closest to the page or view in the directory chain is used. +The preceding relationships apply to import files used with MVC views and Razor components. -### @section +When multiple import files have a `@namespace` directive, the file closest to the page, view, or component in the directory tree is used to set the root namespace. -The `@section` directive is used in conjunction with the [layout](xref:mvc/views/layout) to enable pages or views to render content in different parts of the HTML page. For more information, see [Sections](xref:mvc/views/layout#layout-sections-label). +If the *EvenMorePages* folder in the preceding example has an imports file with `@namespace Another.Planet` (or the *Pages/MorePages/EvenMorePages/Page.cshtml* file contains `@namespace Another.Planet`), the result is shown in the following table. + +| Page | Namespace | +| ------------------------------------------- | ----------------------- | +| *Pages/Index.cshtml* | `Hello.World` | +| *Pages/MorePages/Page.cshtml* | `Hello.World.MorePages` | +| *Pages/MorePages/EvenMorePages/Page.cshtml* | `Another.Planet` | + +### \@page + +::: moniker range=">= aspnetcore-3.0" + +The `@page` directive has different effects depending on the type of the file where it appears. The directive: + +* In in a *.cshtml* file indicates that the file is a Razor Page. For more information, see . +* Specifies that a Razor component should handle requests directly. For more information, see . + +::: moniker-end + +::: moniker range="< aspnetcore-3.0" + +The `@page` directive on the first line of a *.cshtml* file indicates that the file is a Razor Page. For more information, see . + +::: moniker-end + +### \@section + +*This scenario only applies to MVC views and Razor Pages (.cshtml).* + +The `@section` directive is used in conjunction with [MVC and Razor Pages layouts](xref:mvc/views/layout) to enable views or pages to render content in different parts of the HTML page. For more information, see . + +### \@using + +The `@using` directive adds the C# `using` directive to the generated view: + +[!code-cshtml[](razor/sample/Views/Home/Contact9.cshtml)] + +::: moniker range=">= aspnetcore-3.0" + +In [Razor components](xref:blazor/components), `@using` also controls which components are in scope. + +::: moniker-end + +::: moniker range=">= aspnetcore-3.0" + +## Directive attributes + +### \@attributes + +*This scenario only applies to Razor components (.razor).* + +`@attributes` allows a component to render non-declared attributes. For more information, see . + +### \@bind + +*This scenario only applies to Razor components (.razor).* + +Data binding in components is accomplished with the `@bind` attribute. For more information, see . + +### \@on{event} + +*This scenario only applies to Razor components (.razor).* + +Razor provides event handling features for components. For more information, see . + +### \@key + +*This scenario only applies to Razor components (.razor).* + +The `@key` directive attribute causes the components diffing algorithm to guarantee preservation of elements or components based on the key's value. For more information, see . + +### \@ref + +*This scenario only applies to Razor components (.razor).* + +Component references (`@ref`) provide a way to reference a component instance so that you can issue commands to that instance. For more information, see . + +::: moniker-end ## Templated Razor delegates @@ -700,19 +836,21 @@ Rendered output: ## Tag Helpers +*This scenario only applies to MVC views and Razor Pages (.cshtml).* + There are three directives that pertain to [Tag Helpers](xref:mvc/views/tag-helpers/intro). | Directive | Function | | --------- | -------- | -| [@addTagHelper](xref:mvc/views/tag-helpers/intro#add-helper-label) | Makes Tag Helpers available to a view. | -| [@removeTagHelper](xref:mvc/views/tag-helpers/intro#remove-razor-directives-label) | Removes Tag Helpers previously added from a view. | -| [@tagHelperPrefix](xref:mvc/views/tag-helpers/intro#prefix-razor-directives-label) | Specifies a tag prefix to enable Tag Helper support and to make Tag Helper usage explicit. | +| [@addTagHelper](xref:mvc/views/tag-helpers/intro#add-helper-label) | Makes Tag Helpers available to a view. | +| [@removeTagHelper](xref:mvc/views/tag-helpers/intro#remove-razor-directives-label) | Removes Tag Helpers previously added from a view. | +| [@tagHelperPrefix](xref:mvc/views/tag-helpers/intro#prefix-razor-directives-label) | Specifies a tag prefix to enable Tag Helper support and to make Tag Helper usage explicit. | ## Razor reserved keywords ### Razor keywords -* page (Requires ASP.NET Core 2.0 and later) +* page (Requires ASP.NET Core 2.1 or later) * namespace * functions * inherits diff --git a/aspnetcore/mvc/views/razor/sample/Classes/CustomRazorPage.cs b/aspnetcore/mvc/views/razor/sample/Classes/CustomRazorPage.cs index 39e2035179..7a94ff0154 100644 --- a/aspnetcore/mvc/views/razor/sample/Classes/CustomRazorPage.cs +++ b/aspnetcore/mvc/views/razor/sample/Classes/CustomRazorPage.cs @@ -2,5 +2,7 @@ public abstract class CustomRazorPage : RazorPage { - public string CustomText { get; } = "Gardyloo! - A Scottish warning yelled from a window before dumping a slop bucket on the street below."; + public string CustomText { get; } = + "Gardyloo! - A Scottish warning yelled from a window before dumping" + + "a slop bucket on the street below."; }