Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 41 ยท Components and Razor Syntax

Razor Syntax Basics

Learn Razor syntax for Blazor components: @ expressions, implicit and explicit expressions, code blocks, directives like @using and @inject, escaping the @ symbol, comments and raw HTML.

Razor is the mini-language that lets you mix C# into HTML. Every Blazor component uses it, so a solid grip on a handful of rules pays off everywhere. The central idea: the @ symbol switches from HTML to C#. Razor is clever about where the C# ends, but there are a few edge cases where you have to help it.

Implicit expressions

@ followed by an identifier writes its value into the HTML. The expression ends at the first character that cannot be part of it, such as a space or <.

HTML
<p>Hello, @userName!</p>
<p>You have @messages.Count new messages.</p>
<p>Today is @DateTime.Now.DayOfWeek.</p>
<p>Total: @order.Total.ToString("C")</p>

Razor accepts dotted member access, indexers and method calls with parentheses. Values are HTML-encoded automatically, so a string like <script> shows as text and cannot inject markup. That default protects you from cross-site scripting.

Explicit expressions

Use @( ... ) when Razor would guess wrong, or when you need operators:

HTML
<p>Next year: @(year + 1)</p>
<p>Price with tax: @(price * 1.2m)</p>
<p>Item_@(index)_label</p>

Without the parentheses, @year + 1 prints the value of year followed by the text " + 1". Razor does not treat + as part of the expression.

Code blocks

@{ ... } runs statements without producing output, handy for local variables:

HTML
@{
    var greeting = DateTime.Now.Hour < 12 ? "Good morning" : "Hello";
    var shout = greeting.ToUpper();
}
<h2>@shout</h2>

Inside a code block you can switch back to markup, either by writing a full HTML element or with the @: prefix for a single line of text:

HTML
@{
    var items = new[] { "a", "b" };
    foreach (var item in items)
    {
        <li>@item</li>
    }
    @:Plain text line with @items.Length items
}

The @code block

A component's fields, properties and methods live in @code { ... }. It is a normal C# class body:

HTML
<p>@Describe(count)</p>

@code {
    private int count = 3;

    private string Describe(int n) => n == 1 ? "one item" : $"{n} items";
}

You can have more than one @code block, but a single one at the bottom of the file is the convention. Use @functions only if you want the older name; it does the same.

Directives

Directives begin with @ at the top of the file and configure the component:

Directive Purpose
@page "/route" Make the component routable
@using Some.Namespace Import a namespace
@inject IService Service Request a dependency (chapter 6)
@inherits BaseClass Use a different base class
@implements IDisposable Implement an interface
@attribute [Authorize] Add a C# attribute to the class
@typeparam TItem Declare a generic type parameter
@rendermode InteractiveServer Choose the render mode
@layout MainLayout Choose a layout

Escaping and special cases

An email address is not code. Razor recognises [email protected] as text because @ in the middle of a word with text on both sides is left alone. To print a literal @ where it could be misread, double it:

HTML
<p>Follow us @@blazor_dev</p>

HTML attributes can hold expressions too:

HTML
<a href="/users/@userId">Profile</a>
<div class="card @(isActive ? "active" : "")">...</div>
<input disabled="@isLocked" />

For boolean attributes like disabled and checked, a true value renders the attribute and false removes it entirely. That is more useful than writing disabled="false", which would not mean "enabled" in HTML.

Comments and raw HTML

Razor comments are removed from the output:

HTML
@* This note never reaches the browser *@
<!-- This HTML comment does reach the browser -->

To output HTML you trust without encoding, wrap it in a MarkupString:

HTML
@((MarkupString)formattedHtml)

@code {
    private string formattedHtml = "<strong>Bold</strong> text";
}

Never put user-supplied text into a MarkupString. It bypasses the encoding that prevents cross-site scripting. Use it only for HTML you wrote or that you have sanitized.

Runnable stand-in: a tiny @ substitution engine

Razor is compiled by the framework, so here is a deliberately simple stand-in. It replaces @name and @(expr)-like tokens in a template using a dictionary, HTML-encodes values, and supports the @@ escape. It demonstrates the encode-by-default rule, not the real compiler.

C# Stand-in: @ substitution with encoding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice how <b> in the name is encoded and displayed as text, and how @@ survives as a single @.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which syntax prints year + 1 as a number?

    Explicit expressions in parentheses let you use operators. Without them, + 1 would be literal text.
  2. 2. What happens to a value like <script> when you write @text?

    Razor HTML-encodes output by default, protecting against cross-site scripting.
  3. 3. How do you print a literal @ sign in a component?

    Doubling the symbol, @@, produces one @.
  4. 4. What does <input disabled="@isLocked" /> render when isLocked is false?

    For boolean attributes, true renders the attribute and false removes it.

Summary

  • @ switches from HTML to C#; implicit expressions end at the first non-expression character.
  • Use @( ... ) for operators and @{ ... } for statements; @: writes a line of text in a block.
  • Fields, properties and methods go in @code; directives like @page, @using and @inject sit at the top.
  • Output is HTML-encoded; MarkupString bypasses that and is dangerous with untrusted data.
  • Boolean attributes render only when true; @@ prints a literal @.

Next: Component Parameters