Introduction to Razor Syntax: Fundamentals and Getting Started

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

Welcome to this introductory guide to Razor Syntax! If you are taking your first steps in web development with ASP.NET or want to learn how to create dynamic web pages easily, you are in the right place. In this article, we will explore what Razor is, how it works, its history, and the foundational concepts you need to start using it with confidence. With a clear and practical approach designed for beginners, let’s dive into the world of Razor and discover how to build modern web applications.

1. Introduction to Razor Syntax

What is Razor?

Razor is a templating engine created by Microsoft that lets you blend HTML markup with server-side code, such as C#, in a natural and fluid way. It is an open-source tool that simplifies the creation of dynamic web pages across the ASP.NET ecosystem. With Razor, you can embed logic directly into your HTML files, allowing content to be generated dynamically based on your application’s needs. Files using Razor typically carry the .cshtml extension, combining C# and HTML in one place.

Think of Razor as a bridge connecting your page’s presentation layer (HTML) with your application logic (C#). Instead of keeping markup and server code in completely separate files, Razor lets you write C# expressions right where you need them within HTML. This speeds up development and makes your templates much easier to read and maintain.

Basic example:

<h1>Bienvenido, @Usuario.Nombre!</h1>
<p>La fecha actual es: @DateTime.Now.ToShortDateString()</p>

In this example, @Usuario.Nombre and @DateTime.Now.ToShortDateString() are C# code snippets evaluated by the server before sending the page to the browser. When users visit the page, they only see the final rendered output, such as “Welcome, Ana!” or “The current date is: 26/04/2025”.

History and Evolution

Razor was introduced with ASP.NET Web Pages—part of WebMatrix—as a lightweight, approachable alternative to the rigid Web Forms model. Its simplicity and power quickly won over developers, prompting Microsoft to integrate it across the broader ASP.NET ecosystem. Here is an overview of its evolution:

  • ASP.NET MVC: Razor became the default view engine (though others can still be used). In MVC, Razor lets you build views that consume strongly typed models, resulting in well-organized, testable, and reusable presentation code.
  • Razor Pages: This model streamlines page-focused web development by organizing features into individual .cshtml files that pair markup with handler logic. Each page typically includes a code-behind file (called a PageModel) to process requests.
  • Blazor: A modern UI framework using Razor components to build rich, interactive web frontends. With Blazor, you can run components directly in the browser via WebAssembly or on the server with real-time SignalR updates, all using C# and Razor syntax.

This evolution demonstrates Razor’s versatility. Whether you are building traditional server-rendered web apps, lightweight pages, or full single-page interactive applications, Razor delivers a consistent, developer-friendly experience.

Advantages of Razor

Why choose Razor for your projects? Here are a few key benefits:

  • Clean and readable code: Razor minimizes the boilerplate required to combine HTML and C#. Compared to older technologies like Web Forms, the resulting templates have minimal visual noise, making it straightforward to follow UI logic.
  • Easy to maintain: Thanks to its intuitive syntax, reviewing and updating views remains simple even long after writing them—a critical benefit for long-term project maintainability.
  • First-class Microsoft tooling: Razor integrates seamlessly with Visual Studio and Visual Studio Code. You get full IntelliSense code completion, type checking, refactoring, and debugging out of the box.
  • Architectural flexibility: Razor adapts to different development patterns, including MVC, Razor Pages, and Blazor. No matter your project architecture, your templating skills remain transferable.

2. Basic Razor Syntax

The appeal of Razor lies in its simplicity: using a few simple rules and the @ symbol, you can combine HTML and C# effortlessly. In this section, we will cover the core syntax rules so you can start writing dynamic templates immediately.

Transitions with @

The @ symbol is the core transition character in Razor. It tells the parser: “C# code starts here!”. Using @, you can output expressions or declare code blocks directly in your markup, and Razor will evaluate them on the server before generating the final HTML response.

Simple example:

<p>El año actual es: @DateTime.Now.Year</p>

Here, @DateTime.Now.Year is replaced by the current year (for example, “2025”) when the page renders. Razor automatically determines where code ends and HTML resumes, eliminating the need to explicitly close single-line expressions.

Implicit and Explicit Expressions

Razor provides two ways to inline C# expressions: implicit and explicit.

Implicit expressions: Ideal for rendering simple values such as variables, properties, or short method calls. You simply write @ followed by the C# identifier, and Razor infers where the expression ends.

<p>El nombre es: @variableNombre</p>
<p>La fecha es: @ObtenerFecha()</p>
<p>El título es: @Model.Propiedad</p>

Razor recognizes that variableNombre, ObtenerFecha(), and Model.Propiedad are self-contained expressions and evaluates them directly into the markup.

Explicit expressions: When writing expressions that include arithmetic operations, string concatenation, or generic method calls, Razor’s parser might not deduce the boundary of the expression correctly. In these cases, wrap the expression in parentheses using @(...) to define its scope explicitly.

<p>El resultado es: @(miVariable + otraVariable * 2)</p>
<p>@{ /* Esto es un bloque de código, no una expresión */ }</p>

Notice the distinction: explicit expressions using @(...) evaluate directly to a value written to the output stream, whereas code blocks using @{ ... } (covered next) execute logic without directly writing output.

Code Blocks

When you need to execute multi-line logic—such as declaring local variables, running loops, or evaluating conditional branches—code blocks are the solution. Defined with @{ ... }, they allow you to write standard C# code within your view. Code inside a block is executed on the server and does not render text directly unless explicitly printed with @.

You can also integrate control structures like @if, @foreach, @for, and @while directly with HTML.

Practical example:

@{
    var mensaje = "Hola desde el bloque de código!";
    var numeroItems = 5;
}

<h2>@mensaje</h2>

@if (numeroItems > 0)
{
    <p>Tenemos @numeroItems elementos:</p>
    <ul>
        @for (int i = 0; i < numeroItems; i++)
        {
            <li>Elemento @(i + 1)</li>
        }
    </ul>
}
else
{
    <p>No hay elementos disponibles.</p>
}

In this snippet, we declare local variables inside a @{ ... } block, print the message with @mensaje, and use @if alongside @for to dynamically generate an HTML list. Razor transitions effortlessly between C# control flow and raw HTML tags like <p> and <li>.

Comments in Razor

Clear comments are essential for documenting templates. Razor provides multiple comment strategies depending on your scope:

Razor comments: Use @* ... *@ to write comments evaluated solely by the Razor engine. These comments are stripped out entirely during server rendering and never appear in the client’s HTML source.

@* Este es un comentario de Razor, no aparecerá en el HTML final *@
<p>Contenido visible.</p>
@*
   Este es un comentario de Razor multilinea.
   Muy útil para explicaciones más largas.
*@

C# comments: Inside a @{ ... } code block, you can use standard C# comment syntax: // for single-line comments or /* ... */ for multi-line blocks.

@{
   // Este es un comentario de C# de una sola línea
   var dato = 123;
   /*
      Este es un comentario
      de C# multilinea.
   */
   var otroDato = 456;
}

HTML comments: You can also use standard HTML comments (<!-- ... -->), but keep in mind that these are transmitted over the wire and remain visible to anyone inspecting the page source in the browser.

3. Additional Razor Features

Beyond basic syntax, Razor includes built-in directives and utilities that help structure and configure your views.

Reserved Directives

Razor directives are specialized keywords prefixed with @ that manage view configurations, models, and layout behavior. Here are the most common ones:

@model <Type>: Declares the expected model type for the view. This exposes the strongly typed @Model property and enables full IntelliSense and compile-time validation in your IDE.

@model MiProyecto.Models.Usuario

<h2>Perfil de @Model.Nombre</h2>
<p>Email: @Model.Email</p>

With this directive in place, the view understands it is bound to a Usuario instance and can access properties like Nombre or Email safely.

@layout <Path>: Specifies the master layout template for the view. Layouts define common structural markup—such as navigation headers and footers—avoiding repetitive code across pages.

@layout "~/Views/Shared/_Layout.cshtml"

<h1>Contenido específico de la página</h1>

@section <Name>: Defines a block of content intended to be injected into a matching @RenderSection placeholder inside the layout template, commonly used for page-specific stylesheets or scripts.

@section Scripts {
    <script src="~/js/pagina.js"></script>
}

<h1>Mi Página con Script Específico</h1>

@functions { ... }: Allows you to declare helper methods, properties, or fields directly within the .cshtml file. While useful for quick helpers, complex logic should generally reside in dedicated classes or PageModels.

@functions {
    public string ObtenerSaludo(string nombre)
    {
        return $"¡Hola, {nombre}!";
    }
}

<p>@ObtenerSaludo("Visitante")</p>

@page: Configures a .cshtml file as a Razor Page, enabling it to route and resolve incoming HTTP requests directly without an MVC controller.

@page
@model IndexModel

<h1>Página de Inicio de Razor Pages</h1>
<p>@Model.Mensaje</p>

Escaping with @@

If you need to render a literal @ character in your HTML—such as within an email address or username handle—writing a single @ can cause Razor to expect C# code. Escape it by typing @@, which outputs a single literal @ character.

<p>Mi dirección de correo es: usuario@@dominio.com</p>
<p>El símbolo de Razor es: @@</p>

The browser renders: [email protected] and The Razor symbol is: @.

Embedded Content (SVG, JavaScript, etc.)

Razor views accommodate embedded assets like inline SVGs, <script> tags, and <style> blocks without special wrappers. Simply write standard markup, and ensure you only use @ when you intentionally want to evaluate server-side expressions inside those assets.

Example:

<svg width="100" height="100">
    <circle cx="50" cy="50" r="40" fill="blue" />
</svg>

<script>
    // JavaScript dentro de una vista Razor
    console.log('Hola desde un script en Razor!');
    var userName = '@Model.Nombre'; // ¡Puedes incrustar C# aquí!
    console.log('Usuario: ' + userName);
</script>

Applications and Use in Projects

Razor Syntax forms the presentation backbone for multiple application paradigms in ASP.NET Core. Depending on your project requirements, you will encounter Razor across three primary architectures: ASP.NET Core MVC, Razor Pages, and Blazor.

ASP.NET Core MVC

In the Model-View-Controller (MVC) pattern, Razor is used within view files (.cshtml). Views receive data passed from a controller—typically wrapped in a ViewModel—and render dynamic HTML responses. Razor makes it easy to generate dynamic tables, conditional status badges, and input forms based on incoming view models.

Practical example:

@model List<MiProyecto.Models.Producto>
@{
    ViewData["Title"] = "Lista de Productos"; // Esto pasa el título al layout
}

<h1>@ViewData["Title"]</h1>

@if (Model != null && Model.Any())
{
    <ul>
        @foreach (var producto in Model)
        {
            <li>@producto.Nombre - @producto.Precio.ToString("C")</li> @* Formato de moneda *@
        }
    </ul>
}
else
{
    <p>No hay productos disponibles.</p>
}

In this example, @model specifies that the view consumes an IEnumerable<Producto>. We use @ViewData to set the page title for the layout. Using @if and @foreach, Razor renders each product’s details and applies currency formatting to prices ($19.99). If the collection is empty, a fallback alert is rendered.

Razor Pages

For page-focused workflows, Razor Pages provides a cleaner alternative to MVC. Each .cshtml file represents an addressable route combining HTML presentation with request handlers. Logic is isolated in a companion code-behind class (.cshtml.cs) inheriting from PageModel, which handles actions like OnGet and OnPost. The @page directive at the top of the file designates it as a Razor Page.

Practical example:

@page
@model MiProyecto.Pages.IndexModel
@{
    ViewData["Title"] = "Página de Inicio";
}

<h1>@ViewData["Title"]</h1>

<p>Bienvenido a la página de inicio.</p>

@if (!string.IsNullOrEmpty(Model.MensajeBienvenida))
{
    <p>Mensaje: @Model.MensajeBienvenida</p>
}

Here, @page declares the route, and @model binds the view to its IndexModel. We set view metadata via @ViewData and conditionally output a greeting if Model.MensajeBienvenida contains data. This model is well-suited for CRUD interfaces, administrative dashboards, and content-driven web portals.

Blazor

For rich, single-page client applications, Blazor leverages Razor syntax to build reusable UI components. Blazor applications run C# directly in the browser via WebAssembly or process UI diffs on the server via SignalR. Instead of relying on client-side JavaScript frameworks, you build modular components combining HTML, C# state, and event bindings in .razor files.

Practical example:

@page "/contador"

<h1>Contador</h1>

<p>Valor actual: @contador</p>
<button @onclick="Incrementar">Aumentar</button>

@code {
    private int contador = 0;

    private void Incrementar()
    {
        contador++;
    }
}

In this component, @page "/contador" sets up client-side routing. The markup binds an onclick event directly to the C# Incrementar method declared inside the @code block. When the button is clicked, Blazor updates component state and re-renders the DOM automatically without full page reloads.

Razor Syntax

Razor Syntax is a foundational, accessible tool for building dynamic web applications across the ASP.NET ecosystem. Its concise syntax centered around the @ transition character allows you to seamlessly weave C# logic into HTML, while built-in directives like @model and @page give you clear control over routing, data binding, and layout structure. Whether you are maintaining an MVC application, structuring modular workflows with Razor Pages, or developing interactive components in Blazor, mastering Razor is an essential step in modern .NET web development.

With practical experimentation, you will quickly appreciate how easily Razor adapts across diverse project requirements. Keep experimenting, writing clean templates, and exploring what Razor brings to your ASP.NET projects!