--- title: Razor Syntax Reference author: rick-anderson ms.author: riande manager: wpickett ms.date: 10/14/2016 ms.topic: article ms.assetid: a89a8433-8b0e-4795-a73a-82114d27e233 ms.prod: aspnet-core uid: mvc/views/razor --- # Razor Syntax Reference [Taylor Mullen](https://twitter.com/ntaylormullen) and [Rick Anderson](https://twitter.com/RickAndMSFT) ## What is Razor? Razor is a markup syntax for embedding server based code into web pages. The Razor syntax consists of Razor markup, C# and HTML. Files containing Razor generally have a *.cshtml* file extension. ## Rendering HTML The default Razor language is HTML. Rendering HTML from Razor is no different than in an HTML file. A Razor file with the following markup: ````html

Hello World

```` Is rendered unchanged as `

Hello World

` by the server. ## Razor syntax Razor supports C# and uses the `@` symbol to transition from HTML to C#. Razor evaluates C# expressions and renders them in the HTML output. Razor can transition from HTML into C# or into Razor specific markup. When an `@` symbol is followed by a it transitions into Razor specific markup, otherwise it transitions into plain C# . HTML containing `@` symbols may need to be escaped with a second `@` symbol. For example: ````html

@@Username

```` would render the following HTML: ````html

@Username

```` HTML attributes and content containing email addresses don’t treat the `@` symbol as a transition character. `Support@contoso.com` ## Implicit Razor expressions Implicit Razor expressions start with `@` followed by C# code. For example: ````html

@DateTime.Now

@DateTime.IsLeapYear(2016)

```` With the exception of the C# `await` keyword implicit expressions must not contain spaces. For example, you can intermingle spaces as long as the C# statement has a clear ending: ````html

@await DoSomething("hello", "world")

```` ## Explicit Razor expressions Explicit Razor expressions consists of an @ symbol with balanced parenthesis. For example, to render last weeks’ time: ````html

Last week this time: @(DateTime.Now - TimeSpan.FromDays(7))

```` Any content within the @() parenthesis is evaluated and rendered to the output. Implicit expressions generally cannot contain spaces. For example, in the code below, one week is not subtracted from the current time: [!code-html[Main](razor/sample/Views/Home/Contact.cshtml?range=20)] Which renders the following HTML: ````html

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

```` You can use an explicit expression to concatenate text with an expression result: ````none @{ var joe = new Person("Joe", 33); }

Age@(joe.Age)

```` Without the explicit expression, `

Age@joe.Age

` would be treated as an email address and `

Age@joe.Age

` would be rendered. When written as an explicit expression, `

Age33

` is rendered. ## Expression encoding C# expressions that evaluate to a string are HTML encoded. C# expressions that evaluate to [`IHtmlContent`](http://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNetCore/Html/IHtmlContent/index.html#Microsoft.AspNetCore.Html.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 are rendered. For example, the following Razor markup: ````html @("Hello World") ```` Renders this HTML: ````html <span>Hello World</span> ```` Which the browser renders as: `Hello World` [`HtmlHelper`](http://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNetCore/Mvc/ViewFeatures/HtmlHelper/index.html#Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelper) [`Raw`](http://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNetCore/Mvc/ViewFeatures/HtmlHelper/index.html#Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelper.Raw) output is not encoded but rendered as HTML markup. >[!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` on user input. The following Razor markup: ````html @Html.Raw("Hello World") ```` Renders this HTML: ````html Hello World ```` ## Razor code blocks Razor code blocks start with `@` and are enclosed by `{}`. Unlike expressions, C# code inside code blocks is not rendered. Code blocks and expressions in a Razor page share the same scope and are defined in order (that is, declarations in a code block will be in scope for later code blocks and expressions). ````none @{ var output = "Hello World"; }

The rendered result: @output

```` Would render: ````html

The rendered result: Hello World

```` ### Implicit transitions The default language in a code block is C#, but you can transition back to HTML. HTML within a code block will transition back into rendering HTML: ````none @{ var inCSharp = true;

Now in HTML, was in C# @inCSharp

} ```` ### Explicit delimited transition To define a sub-section of a code block that should render HTML, surround the characters to be rendered with the Razor `` tag: ````none @for (var i = 0; i < people.Length; i++) { var person = people[i]; Name: @person.Name } ```` You generally use this approach when you want to render HTML that is not surrounded by an HTML tag. Without an HTML or Razor tag, you get a Razor runtime error. ### Explicit Line Transition with `@:` To render the rest of an entire line as HTML inside a code block, use the `@:` syntax: ````none @for (var i = 0; i < people.Length; i++) { var person = people[i]; @:Name: @person.Name } ```` Without the `@:` in the code above, you'd get a Razor run time error. ## 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` The `@if` family controls when code runs: ````none @if (value % 2 == 0) {

The value was even

} ```` `else` and `else if` don't require the `@` symbol: ````none @if (value % 2 == 0) {

The value was even

} else if (value >= 1337) {

The value is large.

} else {

The value was not large and is odd.

} ```` You can use a switch statement like this: ````none @switch (value) { case 1:

The value is 1!

break; case 1337:

Your number is 1337!

break; default:

Your number was not 1 or 1337.

break; } ```` ### Looping `@for`, `@foreach`, `@while`, and `@do while` You can render templated HTML with looping control statements. For example, to render a list of people: ````none @{ var people = new Person[] { new Person("John", 33), new Person("Doe", 41), }; } ```` You can use any of the following looping statements: `@for` ````none @for (var i = 0; i < people.Length; i++) { var person = people[i];

Name: @person.Name

Age: @person.Age

} ```` `@foreach` ````none @foreach (var person in people) {

Name: @person.Name

Age: @person.Age

} ```` `@while` ````none @{ var i = 0; } @while (i < people.Length) { var person = people[i];

Name: @person.Name

Age: @person.Age

i++; } ```` `@do while` ````none @{ var i = 0; } @do { var person = people[i];

Name: @person.Name

Age: @person.Age

i++; } while (i < people.Length); ```` ### Compound `@using` In C# a using statement is used to ensure an object is disposed. In Razor this same mechanism can be used to create [HTML helpers](html-helpers.md) that contain additional content. For instance, we can utilize [🔧 HTML Helpers](html-helpers.md) to render a form tag with the `@using` statement: ````none @using (Html.BeginForm()) {
email:
} ```` You can also perform scope level actions like the above with [Tag Helpers](tag-helpers/index.md). ### `@try`, `catch`, `finally` Exception handling is similar to C#: [!code-html[Main](razor/sample/Views/Home/Contact7.cshtml)] ### `@lock` Razor has the capability to protect critical sections with lock statements: ````none @lock (SomeLock) { // Do critical section work } ```` ### Comments Razor supports C# and HTML comments. The following markup: ````none @{ /* C# comment. */ // Another C# comment. } ```` Is rendered by the server as: ````none ```` Razor comments are removed by the server before the page is rendered. Razor uses `@* *@` to delimit comments. The following code is commented out, so the server will not render any markup: ````none @* @{ /* C# comment. */ // Another C# comment. } *@ ```` ## Directives Razor directives are represented by implicit expressions with reserved keywords following the `@` symbol. A directive will typically change the way a page is parsed or enable different functionality within your Razor page. Understanding how Razor generates code for a view will make it easier to understand how directives work. A Razor page is used to generate a C# file. For example, this Razor page: [!code-html[Main](razor/sample/Views/Home/Contact8.cshtml)] Generates a class similar to the following: ````csharp public class _Views_Something_cshtml : RazorPage { public override async Task ExecuteAsync() { var output = "Hello World"; WriteLiteral("/r/n
Output: "); Write(output); WriteLiteral("
"); } } ```` explains how to view this generated class. ### `@using` The `@using` directive will add the c# `using` directive to the generated razor page: [!code-html[Main](razor/sample/Views/Home/Contact9.cshtml)] ### `@model` The `@model` directive allows you to specify the type of the model passed to your Razor page. It uses the following syntax: ````none @model TypeNameOfModel ```` For example, if you create an ASP.NET Core MVC app with individual user accounts, the *Views/Account/Login.cshtml* Razor view contains the following model declaration: ````csharp @model LoginViewModel ```` In the class example in , the class generated inherits from `RazorPage`. By adding an `@model` you control what’s inherited. For example ````csharp @model LoginViewModel ```` Generates the following class ````csharp public class _Views_Account_Login_cshtml : RazorPage ```` Razor pages expose a `Model` property for accessing the model passed to the page. ````html
The Login Email: @Model.Email
```` The `@model` directive specified the type of this property (by specifying the `T` in `RazorPage` that the generated class for your page derives from). If you don't specify the `@model` directive the `Model` property will be of type `dynamic`. The value of the model is passed from the controller to the view. See [Strongly typed models and the @model keyword](../../tutorials/first-mvc-app/adding-model.md#strongly-typed-models-keyword-label) for more information. ### `@inherits` The `@inherits` directive gives you full control of the class your Razor page inherits: ````none @inherits TypeNameOfClassToInheritFrom ```` For instance, let’s say we had the following custom Razor page type: [!code-csharp[Main](razor/sample/Classes/CustomRazorPage.cs)] The following Razor would generate `
Custom text: Hello World
`. [!code-html[Main](razor/sample/Views/Home/Contact10.cshtml)] You can't use `@model` and `@inherits` on the same page. You can have `@inherits` in a *_ViewImports.cshtml* file that the Razor page imports. For example, if your Razor view imported the following *_ViewImports.cshtml* file: [!code-html[Main](razor/sample/Views/_ViewImportsModel.cshtml)] The following strongly typed Razor page [!code-html[Main](razor/sample/Views/Home/Login1.cshtml)] Generates this HTML markup: ````none
The Login Email: Rick@contoso.com
Custom text: Hello World
```` When passed "[Rick@contoso.com](mailto:Rick@contoso.com)" in the model: See [Layout](layout.md) for more information. ### `@inject` The `@inject` directive enables you to inject a service from your [service container](../../fundamentals/dependency-injection.md) into your Razor page for use. See [Dependency injection into views](dependency-injection.md). ### `@functions` The `@functions` directive enables you to add function level content to your Razor page. The syntax is: ````none @functions { // C# Code } ```` For example: [!code-html[Main](razor/sample/Views/Home/Contact6.cshtml)] Generates the following HTML markup: ````none
From method: Hello
```` The generated Razor C# looks like: [!code-csharp[Main](razor/sample/Classes/Views_Home_Test_cshtml.cs?range=1-19)] ### `@section` The `@section` directive is used in conjunction with the [layout page](layout.md) to enable views to render content in different parts of the rendered HTML page. See [Sections](layout.md#layout-sections-label) for more information. ## TagHelpers The following [Tag Helpers](tag-helpers/index.md) directives are detailed in the links provided. * [@addTagHelper](tag-helpers/intro.md#add-helper-label) * [@removeTagHelper](tag-helpers/intro.md#remove-razor-directives-label) * [@tagHelperPrefix](tag-helpers/intro.md#prefix-razor-directives-label) ## Razor reserved keywords ### Razor keywords * functions * inherits * model * section * helper (Not supported by ASP.NET Core.) Razor keywords can be escaped with `@(Razor Keyword)`, for example `@(functions)`. See the complete sample below. ### C# Razor keywords * case * do * default * for * foreach * if * lock * switch * try * using * while C# Razor keywords need to be double escaped with `@(@C# Razor Keyword)`, for example `@(@case)`. The first `@` escapes the Razor parser, the second `@` escapes the C# parser. See the complete sample below. ### Reserved keywords not used by Razor * namespace * class ## Viewing the Razor C# class generated for a view Add the following class to your ASP.NET Core MVC project: [!code-csharp[Main](razor/sample/Services/CustomCompilationService.cs)] Override the [`ICompilationService`](http://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNetCore/Mvc/Razor/Compilation/ICompilationService/index.html#Microsoft.AspNetCore.Mvc.Razor.Compilation.ICompilationService) added by MVC with the above class; [!code-csharp[Main](razor/sample/Startup.cs?highlight=4&range=29-33)] Set a break point on the `Compile` method of `CustomCompilationService` and view `compilationContent`. ![Text Visualizer view of compilationContent](razor/_static/tvr.png)