Skip to content

Change code language #35585

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 43 additions & 44 deletions aspnetcore/mvc/views/razor.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ When an `@` symbol is followed by a [Razor reserved keyword](#razor-reserved-key

To escape an `@` symbol in Razor markup, use a second `@` symbol:

```cshtml
```razor
<p>@@Username</p>
```

Expand All @@ -38,11 +38,10 @@ The code is rendered in HTML with a single `@` symbol:

HTML attributes and content containing email addresses don't treat the `@` symbol as a transition character. The email addresses in the following example are untouched by Razor parsing:

```cshtml
```razor
<a href="mailto:Support@contoso.com">Support@contoso.com</a>
```


:::moniker range=">= aspnetcore-6.0"

### Scalable Vector Graphics (SVG)
Expand All @@ -69,20 +68,20 @@ HTML attributes and content containing email addresses don't treat the `@` symbo

Implicit Razor expressions start with `@` followed by C# code:

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

With the exception of the C# `await` keyword, implicit expressions must not contain spaces. If the C# statement has a clear ending, spaces can be intermingled:

```cshtml
```razor
<p>@await DoSomething("hello", "world")</p>
```

Implicit expressions **cannot** contain C# generics, as the characters inside the brackets (`<>`) are interpreted as an HTML tag. The following code is **not** valid:

```cshtml
```razor
<p>@GenericMethod<int>()</p>
```

Expand All @@ -97,7 +96,7 @@ Generic method calls must be wrapped in an [explicit Razor expression](#explicit

Explicit Razor expressions consist of an `@` symbol with balanced parenthesis. To render last week's time, the following Razor markup is used:

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

Expand All @@ -115,7 +114,7 @@ The code renders the following HTML:

Explicit expressions can be used to concatenate text with an expression result:

```cshtml
```razor
@{
var joe = new Person("Joe", 33);
}
Expand All @@ -127,15 +126,15 @@ Without the explicit expression, `<p>Age@joe.Age</p>` is treated as an email add

Explicit expressions can be used to render output from generic methods in `.cshtml` 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:

```cshtml
```razor
<p>@(GenericMethod<int>())</p>
```

## Expression encoding

C# expressions that evaluate to a string are HTML encoded. C# expressions that evaluate to `IHtmlContent` are rendered directly through `IHtmlContent.WriteTo`. C# expressions that don't evaluate to `IHtmlContent` are converted to a string by `ToString` and encoded before they're rendered.

```cshtml
```razor
@("<span>Hello World</span>")
```

Expand All @@ -154,7 +153,7 @@ The HTML is shown in the browser as plain text:
> [!WARNING]
> Using `HtmlHelper.Raw` on unsanitized user input is a security risk. User input might contain malicious JavaScript or other exploits. Sanitizing user input is difficult. Avoid using `HtmlHelper.Raw` with user input.

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

Expand All @@ -168,7 +167,7 @@ The code renders the following HTML:

Razor code blocks start with `@` and are enclosed by `{}`. 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:

```cshtml
```razor
@{
var quote = "The future depends on what you do today. - Mahatma Gandhi";
}
Expand All @@ -191,7 +190,7 @@ The code renders the following HTML:

In code blocks, declare [local functions](/dotnet/csharp/programming-guide/classes-and-structs/local-functions) with markup to serve as templating methods:

```cshtml
```razor
@{
void RenderName(string name)
{
Expand All @@ -214,7 +213,7 @@ The code renders the following HTML:

The default language in a code block is C#, but the Razor Page can transition back to HTML:

```cshtml
```razor
@{
var inCSharp = true;
<p>Now in HTML, was in C# @inCSharp</p>
Expand All @@ -225,7 +224,7 @@ The default language in a code block is C#, but the Razor Page can transition ba

To define a subsection of a code block that should render HTML, surround the characters for rendering with the Razor `<text>` tag:

```cshtml
```razor
@for (var i = 0; i < people.Length; i++)
{
var person = people[i];
Expand All @@ -244,7 +243,7 @@ The `<text>` tag is useful to control whitespace when rendering content:

To render the rest of an entire line as HTML inside a code block, use `@:` syntax:

```cshtml
```razor
@for (var i = 0; i < people.Length; i++)
{
var person = people[i];
Expand All @@ -265,7 +264,7 @@ Razor automatically omits attributes that aren't required. If the value passed i

For example, consider the following Razor markup:

```cshtml
```razor
<div class="@false">False</div>
<div class="@null">Null</div>
<div class="@("")">Empty</div>
Expand Down Expand Up @@ -293,7 +292,7 @@ Razor retains `data-` attributes if their values are `null` or `false`.

Consider the following Razor markup:

```cshtml
```razor
<div data-id="@null" data-active="@false"></div>
```

Expand All @@ -311,7 +310,7 @@ Control structures are an extension of code blocks. All aspects of code blocks (

`@if` controls when code runs:

```cshtml
```razor
@if (value % 2 == 0)
{
<p>The value was even.</p>
Expand All @@ -320,7 +319,7 @@ Control structures are an extension of code blocks. All aspects of code blocks (

`else` and `else if` don't require the `@` symbol:

```cshtml
```razor
@if (value % 2 == 0)
{
<p>The value was even.</p>
Expand All @@ -337,7 +336,7 @@ else

The following markup shows how to use a switch statement:

```cshtml
```razor
@switch (value)
{
case 1:
Expand All @@ -356,7 +355,7 @@ The following markup shows how to use a switch statement:

Templated HTML can be rendered with looping control statements. To render a list of people:

```cshtml
```razor
@{
var people = new Person[]
{
Expand All @@ -371,7 +370,7 @@ The following looping statements are supported:

`@for`

```cshtml
```razor
@for (var i = 0; i < people.Length; i++)
{
var person = people[i];
Expand All @@ -382,7 +381,7 @@ The following looping statements are supported:

`@foreach`

```cshtml
```razor
@foreach (var person in people)
{
<p>Name: @person.Name</p>
Expand All @@ -392,7 +391,7 @@ The following looping statements are supported:

`@while`

```cshtml
```razor
@{ var i = 0; }
@while (i < people.Length)
{
Expand All @@ -406,7 +405,7 @@ The following looping statements are supported:

`@do while`

```cshtml
```razor
@{ var i = 0; }
@do
{
Expand All @@ -422,7 +421,7 @@ The following looping statements are supported:

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:

```cshtml
```razor
@using (Html.BeginForm())
{
<div>
Expand All @@ -442,7 +441,7 @@ Exception handling is similar to C#:

Razor has the capability to protect critical sections with lock statements:

```cshtml
```razor
@lock (SomeLock)
{
// Do critical section work
Expand All @@ -453,7 +452,7 @@ Razor has the capability to protect critical sections with lock statements:

Razor supports C# and HTML comments:

```cshtml
```razor
@{
/* C# comment */
// Another C# comment
Expand All @@ -469,7 +468,7 @@ The code renders the following HTML:

Razor comments are removed by the server before the webpage is rendered. Razor uses `@* *@` to delimit comments. The following code is commented out, so the server doesn't render any markup:

```cshtml
```razor
@*
@{
/* C# comment */
Expand Down Expand Up @@ -509,7 +508,7 @@ Later in this article, the section [Inspect the Razor C# class generated for a v

The `@attribute` directive adds the given attribute to the class of the generated page or view. The following example adds the `[Authorize]` attribute:

```cshtml
```razor
@attribute [Authorize]
```

Expand Down Expand Up @@ -538,7 +537,7 @@ For Razor components, `@code` is an alias of [`@functions`](#functions) and reco

The `@functions` directive enables adding C# members (fields, properties, and methods) to the generated class:

```cshtml
```razor
@functions {
// C# members (fields, properties, and methods)
}
Expand All @@ -562,7 +561,7 @@ The following code is the generated Razor C# class:

`@functions` methods serve as templating methods when they have markup:

```cshtml
```razor
@{
RenderName("Mahatma Gandhi");
RenderName("Martin Luther King, Jr.");
Expand All @@ -589,7 +588,7 @@ The `@implements` directive implements an interface for the generated class.

The following example implements <xref:System.IDisposable?displayProperty=fullName> so that the <xref:System.IDisposable.Dispose*> method can be called:

```cshtml
```razor
@implements IDisposable

<h1>Example</h1>
Expand All @@ -607,7 +606,7 @@ The following example implements <xref:System.IDisposable?displayProperty=fullNa

The `@inherits` directive provides full control of the class the view inherits:

```cshtml
```razor
@inherits TypeNameOfClassToInheritFrom
```

Expand Down Expand Up @@ -662,13 +661,13 @@ The `@layout` directive specifies a layout for routable Razor components that ha

The `@model` directive specifies the type of the model passed to a view or page:

```cshtml
```razor
@model TypeNameOfModel
```

In an ASP.NET Core MVC or Razor Pages app created with individual accounts, `Views/Account/Login.cshtml` contains the following model declaration:

```cshtml
```razor
@model LoginViewModel
```

Expand All @@ -680,7 +679,7 @@ public class _Views_Account_Login_cshtml : RazorPage<LoginViewModel>

Razor exposes a `Model` property for accessing the model passed to the view:

```cshtml
```razor
<div>The Login Email: @Model.Email</div>
```

Expand All @@ -693,7 +692,7 @@ 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
```razor
@namespace Your.Namespace.Here
```

Expand Down Expand Up @@ -895,7 +894,7 @@ Component references (`@ref`) provide a way to reference a component instance so

Razor templates allow you to define a UI snippet with the following format:

```cshtml
```razor
@<tag>...</tag>
```

Expand All @@ -908,7 +907,7 @@ public class Pet
}
```

```cshtml
```razor
@{
Func<dynamic, object> petTemplate = @<p>You have a pet named <strong>@item.Name</strong>.</p>;

Expand All @@ -923,7 +922,7 @@ public class Pet

The template is rendered with `pets` supplied by a `foreach` statement:

```cshtml
```razor
@foreach (var pet in pets)
{
@petTemplate(pet)
Expand All @@ -940,7 +939,7 @@ Rendered output:

You can also supply an inline Razor template as an argument to a method. In the following example, the `Repeat` method receives a Razor template. The method uses the template to produce HTML content with repeats of items supplied from a list:

```cshtml
```razor
@using Microsoft.AspNetCore.Html

@functions {
Expand Down Expand Up @@ -968,7 +967,7 @@ Using the list of pets from the prior example, the `Repeat` method is called wit
* Number of times to repeat each pet.
* Inline template to use for the list items of an unordered list.

```cshtml
```razor
<ul>
@Repeat(pets, 3, @<li>@item.Name</li>)
</ul>
Expand Down