blazor-sintaxis-razor

Razor Syntax: How to Combine HTML and C#

  • 5 min

The Razor syntax allows you to combine HTML markup with C# expressions and code blocks within a single file.

If you come from other frameworks, you might be used to expressions like {{ variable }} or directives like ng-repeat. In Blazor, we use C# for component logic, along with HTML, CSS, and, when needed, JavaScript.

Razor is not a new programming language; it’s a markup syntax that allows embedding server-based code (C#) into web pages.

What’s great about Razor is that it has an “intelligence” to detect transitions. It knows when you’re writing HTML and when you’ve switched to C#, without needing to constantly close tags.

The special symbol: @

In Razor, the @ character is the absolute protagonist. It tells the compiler: “Hey, what comes next is C# code, not text”.

Implicit expressions

This is the most common form. We simply put @ followed by a variable or property.

<h3>Hello, @UserName</h3>
<p>Today is: @DateTime.Now</p>
Copied!

Razor is smart enough to know that UserName is a variable and that when it ends (for example, when it finds a space or an HTML tag), it should interpret the code as HTML again.

Explicit expressions

Sometimes Razor gets confused. For example, if you want to do a simple math operation or concatenate text without spaces. In those cases, we use parentheses @( ... ) to clearly delimit the C# code.

<p>Total: @Price€</p>

<p>Total: @(Price)€</p>

<p>Twice your age is: @(Age * 2)</p>
Copied!

Use explicit expressions @(...) when performing calculations, calling generic methods, or needing to clearly delimit where the code ends.

Code blocks @{ ... }

Sometimes it’s not enough to just print a variable; we need to execute logic (declare local variables, perform complex calculations) before rendering the HTML. For that, we use code blocks.

@{
    var message = "Welcome to the course";
    var isWeekend = DateTime.Now.DayOfWeek == DayOfWeek.Sunday;

    if(isWeekend)
    {
        message += " Happy Sunday!";
    }
}

<div class="alert alert-info">
    @message
</div>
Copied!

It’s important to understand the scope: Variables defined inside a @{ ... } block only exist within the render method at that moment. They are not class properties (for that we use the @code block, which we’ll see later).

Control structures

Razor is especially useful with C# control flow structures (if, switch, foreach), which we can mix directly with HTML.

With a conditional, you decide whether an element is included or not in the render tree. This is not the same as hiding it via CSS, because in this case the element is not generated.

@if (IsLoading)
{
    <p>Loading data...</p>
}
else
{
    <p>Data is ready.</p>
}
Copied!

Generating lists or tables is trivial. We iterate over a C# collection and render HTML in each iteration.

<ul>
    @foreach (var product in ProductList)
    {
        <li>
            <strong>@product.Name</strong> - @product.Price €
        </li>
    }
</ul>
Copied!

Notice the transition: we start with C# (foreach), open a brace {, and when we write the <li> tag, Razor understands we’re back to HTML. When it finds @product, it switches back to the C# context.

Dynamic attributes

We can also use C# to control HTML tag attributes, such as classes, IDs, or input states.

<input type="checkbox" checked="@IsActive" />

<div class="@(IsError ? "bg-red-500" : "bg-green-500")">
    Status message
</div>
Copied!

If the expression value is null or false (for boolean attributes), Razor is smart and removes the attribute entirely from the rendered HTML, keeping the DOM clean.

Basic directives

Directives are special commands that change how the component is compiled or behaves. They start with @ but are usually reserved words.

  • @page: Defines the URL route of the component.
@page "/my-profile"
Copied!
  • @code: The most important block. Here we define the component’s class logic (properties, methods, events).
@code {
    private string Title = "My Web";
    private void Greet() { ... }
}
Copied!
  • @using: Just like in standard C#, it imports namespaces so you don’t have to write System.Collections.Generic.List....
  • @inject: Used for Dependency Injection (we’ll cover it in depth in its own article).

A complete example

Let’s put everything we’ve seen together in a component that simulates a task list.

@page "/tasks"

<h3>My Tasks (@Tasks.Count)</h3>

@if (Tasks.Count == 0)
{
    <div class="alert alert-warning">You have no pending tasks. Time to rest!</div>
}
else
{
    <ul class="list-group">
        @foreach (var task in Tasks)
        {
            <li class="list-group-item @(task.Completed ? "list-group-item-success" : "")">

                <input type="checkbox" checked="@task.Completed" />

                @(task.Completed ? "✅" : "⏳") @task.Description
            </li>
        }
    </ul>
}

@code {
    // Simple class definition within the same file for the example
    public class Task
    {
        public string Description { get; set; }
        public bool Completed { get; set; }
    }

    // Data list
    private List<Task> Tasks = new List<Task>
    {
        new Task { Description = "Learn Razor", Completed = true },
        new Task { Description = "Master Blazor", Completed = false },
        new Task { Description = "Write clean code", Completed = false }
    };
}
Copied!

How to escape a literal @

What happens if you want to display text starting with @, like a username?

Complete email addresses within content or an attribute are normally recognized as text. To write a literal @ in other cases, you must escape it by doubling it:

To solve this, we must escape the @ symbol by doubling it:

<p>Follow me at @@LuisLlamasEs</p>
Copied!

The browser will display @LuisLlamasEs.