# Razor Syntax

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Foundations
Source: https://www.devtutorials.ai/learn/blazor/foundations/razor-syntax

> How Razor mixes HTML and C#: the @ symbol and escaping it, @code blocks with variables and methods, implicit and explicit expressions, raw HTML with MarkupString, @if, @switch and loops, comments, @using and @namespace.

## Razor Overview

- **Razor** is the way you write Blazor components.
- A Razor file ends in `.razor`. It mixes **HTML** (what the page shows) with **C#** (the logic).
- The `@` sign tells Razor: "this part is C#, not HTML".
- When the app runs, Razor works out the C# parts. Then it turns the whole file into plain HTML for the browser.

**Real-World Example:**

- Ravi's order page shows today's date, the customer's name and the total price.
- These values change every time.
- With Razor, he writes the HTML once and drops C# values into it with `@`.

Press **▶ Run**. Each `@` value becomes plain text in the page.

<p>Tea: @tea</p>
<p>Cups: @cups</p>
<p>Date: @DateTime.Today.ToString("dd MMM yyyy")</p>

@code {
      private string customer = "Asha";
      private string tea = "Masala Tea";
      private int cups = 2;
}
`,
  }}
/>

Watch the animation. Razor replaces each `@` part with its value. The browser only ever sees HTML.

<figure className="blz-fig">
<svg viewBox="0 0 640 200" role="img" aria-labelledby="fig-rz-flow">
  <title id="fig-rz-flow">Animation: the line Order for @customer goes into Razor. Razor replaces @customer with Asha. The browser gets Order for Asha as plain HTML.</title>
  <defs><marker id="rz-a1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <text className="t" x="110" y="30" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Your .razor file</text>
  <rect className="pur" x="10" y="44" width="200" height="56" rx="10" />
  <text className="t m" x="110" y="77" textAnchor="middle" style={{ fontSize: 13 }}>Order for <tspan style={{ fill: "#7c3aed", fontWeight: 700 }}>@customer</tspan></text>
  <rect className="org" x="260" y="44" width="120" height="56" rx="10" />
  <text className="t" x="320" y="70" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Razor</text>
  <text className="t" x="320" y="88" textAnchor="middle" style={{ fontSize: 11 }}>works out the @</text>
  <text className="t" x="530" y="30" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>What the browser gets</text>
  <rect className="grn" x="430" y="44" width="200" height="56" rx="10" />
  <text className="t m" x="530" y="77" textAnchor="middle" style={{ fontSize: 13 }}>Order for <tspan style={{ fontWeight: 700 }}>Asha</tspan></text>
  <path className="line" d="M210 72 H256" markerEnd="url(#rz-a1)" />
  <path className="line" d="M380 72 H426" markerEnd="url(#rz-a1)" />
  <rect className="box" x="230" y="130" width="180" height="40" rx="8" />
  <text className="t m" x="320" y="155" textAnchor="middle" style={{ fontSize: 12 }}>customer = "Asha"</text>
  <path className="line" d="M320 130 V104" markerEnd="url(#rz-a1)" style={{ strokeDasharray: "4 4" }} />
  <circle r="6" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="150;320;530" dur="2.6s" repeatCount="indefinite" />
    <animate attributeName="cy" values="110;110;110" dur="2.6s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>@customer is C#. Razor swaps it for its value, so the browser gets plain HTML.</figcaption>
</figure>

**Simple lesson:** Razor is HTML plus C#. The `@` sign marks the C# parts.

## Razor Basics

### The @ Symbol

- `@` switches from HTML to C#.
- After the C# part ends, Razor goes back to HTML by itself.
- You can use `@` for a value (`@tea`), a C# keyword (`@if`, `@foreach`) or a directive (`@page`, `@using`).

### Escaping @

Sometimes you want a real `@` sign on the page. There are two easy ways:

- **Email addresses work as they are.** Razor sees `ravi@teashop.com` and knows it is an email.
- **Write `@@` for one `@`.** For example, `@@RavisTeaShop` shows `@RavisTeaShop`.

<p>Email: ravi@teashop.com</p>
<p>Instagram: @@RavisTeaShop</p>
<p>Open until @closingTime</p>

@code {
      private string closingTime = "9 PM";
}
`,
  }}
/>

- Change `@@RavisTeaShop` to `@RavisTeaShop` and wait a moment. A red line appears, because Razor now looks for a C# name called `RavisTeaShop`.

**Quick rule:** `@` followed by a name means C#. If you want the `@` sign itself, type it twice: `@@`.

**Simple lesson:** `@` starts C#. Use `@@` when you want to show the `@` sign.

## Code Blocks

### @code Block

- `@code { }` holds the C# for your component.
- Put it at the bottom of the `.razor` file, after the HTML.
- Everything inside it belongs to this component only.

### Variables

- A **variable** is a named box that holds a value, like `cups = 2`.
- Write the type, the name and the value: `private int cups = 2;`
- Common types: `string` (text), `int` (whole number), `decimal` (money), `bool` (true or false).
- `private` means only this component can use it.

### Methods

- A **method** is a named set of steps. You can run it again and again.
- A method can **return** a value. `GetTotal()` below returns the price for all cups.
- Use a method in HTML with `@`, like `@GetTotal()`.

<p>@cups cups of @tea</p>
<p>Price per cup: ₹@pricePerCup</p>
<p>Total: ₹@GetTotal()</p>
<p>Paid: @isPaid</p>

@code {
      private string tea = "Ginger Tea";
      private int cups = 3;
      private decimal pricePerCup = 25;
      private bool isPaid = false;

      private decimal GetTotal()
      {
          return cups * pricePerCup;
      }
}
`,
  }}
/>

- Change `cups` to `4` and press **▶ Run**. The total changes, because `GetTotal()` works it out again.

**Simple lesson:** Keep your variables and methods in `@code { }`. Use them in the HTML with `@`.

## Razor Expressions

An **expression** is a piece of C# that gives a value, like `cups` or `cups * pricePerCup`.

### Implicit Expressions

- **Implicit** = `@` followed straight by a name: `@tea`, `@tea.Length`, `@GetTotal()`.
- Razor reads the name, dots and brackets, then stops at the first space.
- That makes it short and easy to read.

### Explicit Expressions

- **Explicit** = `@( ... )` with round brackets.
- Use it when the expression has spaces or maths, like `@(cups * pricePerCup)`.
- Without the brackets, `@cups * 2` shows `3 * 2`. Razor stops reading at the space.

Watch the animation. Razor stops at the space in the first line. The brackets in the second line tell it where the C# ends.

<figure className="blz-fig">
<svg viewBox="0 0 620 190" role="img" aria-labelledby="fig-rz-expr">
  <title id="fig-rz-expr">Animation: in @cups * 2, a highlight covers only @cups and stops at the space, so the page shows 3 * 2. In @(cups * 2), the highlight covers everything inside the brackets, so the page shows 6.</title>
  <text className="t" x="20" y="30" style={{ fontSize: 13, fontWeight: 700 }}>Implicit</text>
  <rect x="120" y="44" width="66" height="30" rx="6" style={{ fill: "#ede9fe" }}>
    <animate attributeName="width" values="0;66;66" keyTimes="0;0.4;1" dur="3s" repeatCount="indefinite" />
  </rect>
  <text className="t m" x="124" y="65" style={{ fontSize: 16 }}>@cups * 2</text>
  <text className="t" x="330" y="65" style={{ fontSize: 13 }}>page shows:</text>
  <rect className="org" x="430" y="44" width="110" height="30" rx="6" />
  <text className="t m" x="485" y="65" textAnchor="middle" style={{ fontSize: 15, fontWeight: 700 }}>3 * 2</text>
  <text className="t" x="20" y="120" style={{ fontSize: 13, fontWeight: 700 }}>Explicit</text>
  <rect x="120" y="134" width="120" height="30" rx="6" style={{ fill: "#ede9fe" }}>
    <animate attributeName="width" values="0;120;120" keyTimes="0;0.6;1" dur="3s" repeatCount="indefinite" />
  </rect>
  <text className="t m" x="124" y="155" style={{ fontSize: 16 }}>@(cups * 2)</text>
  <text className="t" x="330" y="155" style={{ fontSize: 13 }}>page shows:</text>
  <rect className="grn" x="430" y="134" width="110" height="30" rx="6" />
  <text className="t m" x="485" y="155" textAnchor="middle" style={{ fontSize: 15, fontWeight: 700 }}>6</text>
</svg>
<figcaption>Implicit stops at a space. Explicit reads everything inside the brackets.</figcaption>
</figure>

<p>Without brackets: @cups * 2</p>
<p>With brackets: @(cups * 2)</p>
<p>Total: ₹@(cups * pricePerCup)</p>
<p>Message: @($"{cups} cups of {tea}")</p>

@code {
      private string tea = "Masala Tea";
      private int cups = 3;
      private int pricePerCup = 20;
}
`,
  }}
/>

### Raw HTML (MarkupString)

- By default, Razor shows text **as text**. If a variable holds `<b>Hot!</b>`, the page shows the tags as letters.
- This keeps your page safe. Text from a user cannot add its own HTML or scripts.
- To show it as real HTML, wrap it in `MarkupString`: `@((MarkupString)offer)`.

<p>As HTML: @((MarkupString)offer)</p>

@code {
      private string offer = "<b>Buy 2, get 1 free!</b>";
}
`,
  }}
/>

Use `MarkupString` only for HTML **you** wrote. Never use it for text that users type, such as a review or a name. That text could hide harmful code.

**Simple lesson:** Use `@name` for simple values and `@( )` for spaces or maths. Use `MarkupString` only for your own HTML.

## Control Flow

**Control flow** decides which HTML is shown, and how many times. You use normal C# keywords with `@` in front.

### Conditionals (@if, @else if, @else)

- `@if` shows its HTML only when the condition is `true`.
- `else if` checks another condition. `else` runs when nothing above matched.
- The HTML goes inside the curly braces `{ }`.

<figure className="blz-fig">
<svg viewBox="0 0 620 210" role="img" aria-labelledby="fig-rz-if">
  <title id="fig-rz-if">Animation: the value of stock goes into a check. If stock is 0, Sold out is shown. Else if stock is less than 5, Only a few left is shown. Else, In stock is shown. The highlight moves between the three answers as stock changes from 0 to 3 to 20.</title>
  <rect className="box" x="16" y="80" width="120" height="44" rx="8" />
  <text className="t m" x="76" y="100" textAnchor="middle" style={{ fontSize: 12 }}>stock =</text>
  <text className="t m" x="76" y="117" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>
    <tspan>0<animate attributeName="opacity" values="1;0;0;1" keyTimes="0;0.33;0.99;1" dur="6s" repeatCount="indefinite" /></tspan>
  </text>
  <text className="t m" x="76" y="117" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }} opacity="0">3<animate attributeName="opacity" values="0;1;0;0" keyTimes="0;0.33;0.66;1" dur="6s" repeatCount="indefinite" calcMode="discrete" /></text>
  <text className="t m" x="76" y="117" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }} opacity="0">20<animate attributeName="opacity" values="0;0;1" keyTimes="0;0.66;1" dur="6s" repeatCount="indefinite" calcMode="discrete" /></text>
  <rect className="org" x="190" y="80" width="130" height="44" rx="8" />
  <text className="t" x="255" y="107" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>@if / else</text>
  <path className="line" d="M136 102 H186" />
  <path className="line" d="M320 102 L380 40" />
  <path className="line" d="M320 102 H380" />
  <path className="line" d="M320 102 L380 164" />
  <rect className="box" x="384" y="20" width="220" height="40" rx="8">
    <animate attributeName="stroke-width" values="4;1;1;1" keyTimes="0;0.33;0.99;1" dur="6s" repeatCount="indefinite" calcMode="discrete" />
  </rect>
  <text className="t m" x="494" y="45" textAnchor="middle" style={{ fontSize: 12 }}>stock == 0 → Sold out</text>
  <rect className="box" x="384" y="82" width="220" height="40" rx="8" style={{ strokeWidth: 1 }}>
    <animate attributeName="stroke-width" values="1;4;1;1" keyTimes="0;0.33;0.66;1" dur="6s" repeatCount="indefinite" calcMode="discrete" />
  </rect>
  <text className="t m" x="494" y="107" textAnchor="middle" style={{ fontSize: 12 }}>stock &lt; 5 → Only a few left</text>
  <rect className="box" x="384" y="144" width="220" height="40" rx="8" style={{ strokeWidth: 1 }}>
    <animate attributeName="stroke-width" values="1;1;4" keyTimes="0;0.66;1" dur="6s" repeatCount="indefinite" calcMode="discrete" />
  </rect>
  <text className="t m" x="494" y="169" textAnchor="middle" style={{ fontSize: 12 }}>else → In stock</text>
</svg>
<figcaption>Razor checks each condition from the top. The first one that is true wins.</figcaption>
</figure>

@if (stock == 0)
{
      <p>Sold out</p>
}
else if (stock < 5)
{
      <p>Only @stock left. Hurry!</p>
}
else
{
      <p>In stock</p>
}

<button @onclick="SellOne">Sell one cup</button>

@code {
      private int stock = 6;

      private void SellOne()
      {
          if (stock > 0)
          {
              stock--;
          }
      }
}
`,
  }}
/>

- Click **Sell one cup** a few times. The message changes from **In stock** to **Only … left** to **Sold out**.

### Switch (@switch)

- `@switch` picks one case from many, based on one value.
- Each `case` ends with `break;`. `default` runs when no case matches.
- It is neater than a long chain of `else if` when you compare one value.

@switch (size)
{
      case "S":
          <p>Small cup: ₹15</p>
          break;
      case "M":
          <p>Medium cup: ₹20</p>
          break;
      case "L":
          <p>Large cup: ₹30</p>
          break;
      default:
          <p>Please pick S, M or L.</p>
          break;
}

@code {
      private string size = "M";
}
`,
  }}
/>

### Loops (@foreach, @for, @while, @do)

A **loop** repeats HTML. Razor has four kinds:

| Loop | Use it when |
|---|---|
| `@foreach` | You have a list and want one item of HTML per entry. The most common one. |
| `@for` | You want to count, for example from 1 to 5. |
| `@while` | You repeat while a condition is true. |
| `@do` | Like `while`, but it always runs at least once. |

<figure className="blz-fig">
<svg viewBox="0 0 600 170" role="img" aria-labelledby="fig-rz-loop">
  <title id="fig-rz-loop">Animation: a list with Masala, Ginger and Lemon. @foreach picks each one in turn, and a new list item appears on the page for each.</title>
  <text className="t" x="90" y="24" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>menu</text>
  <rect className="box" x="20" y="36" width="140" height="30" rx="6" />
  <text className="t m" x="90" y="56" textAnchor="middle" style={{ fontSize: 12 }}>"Masala"</text>
  <rect className="box" x="20" y="74" width="140" height="30" rx="6" />
  <text className="t m" x="90" y="94" textAnchor="middle" style={{ fontSize: 12 }}>"Ginger"</text>
  <rect className="box" x="20" y="112" width="140" height="30" rx="6" />
  <text className="t m" x="90" y="132" textAnchor="middle" style={{ fontSize: 12 }}>"Lemon"</text>
  <rect className="org" x="220" y="66" width="130" height="44" rx="8" />
  <text className="t" x="285" y="93" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>@foreach</text>
  <circle r="6" cx="185" style={{ fill: "#ea580c" }}>
    <animate attributeName="cy" values="51;89;127" dur="3s" repeatCount="indefinite" calcMode="discrete" />
  </circle>
  <text className="t" x="500" y="24" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Page</text>
  <rect className="grn" x="420" y="36" width="160" height="30" rx="6"><animate attributeName="opacity" values="0;1;1;1" keyTimes="0;0.1;0.9;1" dur="3s" repeatCount="indefinite" /></rect>
  <text className="t m" x="500" y="56" textAnchor="middle" style={{ fontSize: 12 }}>• Masala<animate attributeName="opacity" values="0;1;1" keyTimes="0;0.1;1" dur="3s" repeatCount="indefinite" /></text>
  <rect className="grn" x="420" y="74" width="160" height="30" rx="6" opacity="0"><animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.33;0.43;1" dur="3s" repeatCount="indefinite" /></rect>
  <text className="t m" x="500" y="94" textAnchor="middle" style={{ fontSize: 12 }} opacity="0">• Ginger<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.33;0.43;1" dur="3s" repeatCount="indefinite" /></text>
  <rect className="grn" x="420" y="112" width="160" height="30" rx="6" opacity="0"><animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.66;0.76;1" dur="3s" repeatCount="indefinite" /></rect>
  <text className="t m" x="500" y="132" textAnchor="middle" style={{ fontSize: 12 }} opacity="0">• Lemon<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.66;0.76;1" dur="3s" repeatCount="indefinite" /></text>
  <path className="line" d="M350 88 H414" />
</svg>
<figcaption>@foreach takes each item in turn and adds its HTML to the page.</figcaption>
</figure>

<ul>
      @foreach (var tea in menu)
      {
          <li>@tea</li>
      }
</ul>

<h3>@@for: token numbers</h3>
@for (int i = 1; i <= 3; i++)
{
      <span>Token @i </span>
}

<h3>@@while: fill the pot</h3>
@{ int cups = 0; }
@while (cups < 3)
{
      cups++;
      <p>Poured cup @cups</p>
}

<h3>@@do: runs at least once</h3>
@{ int tries = 5; }
@do
{
      <p>Checking the kettle (try @tries)</p>
      tries++;
} while (tries < 3);

@code {
      private string[] menu = { "Masala Tea", "Ginger Tea", "Lemon Tea" };
}
`,
  }}
/>

- Look at the `@do` loop. `tries` starts at 5, so `tries < 3` is false. It still runs **once**, because `do` checks the condition at the end.
- `@{ ... }` is a small C# block inside the HTML. Here it makes a variable just for that loop.

**Simple lesson:** Use `@if` and `@switch` to choose what to show, and loops to repeat it. Put the HTML inside `{ }`.

## Directives and Comments

### Comments (@* *@)

- A **comment** is a note for people. It is not part of the page.
- Razor comments look like `@* your note *@`.
- They never reach the browser. HTML comments (`<!-- -->`) **are** sent to the browser, so anyone can read them with "View source".

Inside `@code { }`, you write normal C# comments: `// one line` or `/* many lines */`.

### @using and @namespace

- A **directive** is a special line that starts with `@`. It sets something up for the whole file. `@page` is one you already know.
- `@using` lets the file use classes from a **namespace** (a group of classes). For example, `@using System.Text` gives you `StringBuilder`, which joins many pieces of text into one.
- `@namespace` puts this component in a namespace you choose. Most of the time you do not need it. Blazor uses the folder names.

<!-- This HTML comment IS sent to the browser. -->
<p>@GetReceipt()</p>

@code {
      // A C# comment: StringBuilder comes from System.Text.
      private string GetReceipt()
      {
          var text = new StringBuilder();
          text.Append("2 Masala Tea, ");
          text.Append("1 Ginger Tea. ");
          text.Append("Total: ₹65");
          return text.ToString();
      }
}
`,
  }}
/>

- Delete the `@using System.Text` line. A red line appears under `StringBuilder`, because the file can no longer find it.
- Put it back, and the red line goes away.

Here is `@namespace` in a real file. You will rarely need it:

`}
/>

- This component's full name is now `BlazorApp.Shop.Menu`, not `BlazorApp.Components.Pages.Menu`.
- To use it from another folder, that file needs `@using BlazorApp.Shop`.

**Simple lesson:** `@* *@` hides notes from the browser. `@using` brings in classes. `@namespace` sets where your component lives.

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `@cups * 2` to do maths | Razor reads the whole line as C# | Write `@(cups * 2)` | The page shows `3 * 2` |
| Typing `@` for a real at sign before a word | One `@` is just text | Write `@@` | Razor looks for a C# name and shows an error |
| Showing user text with `MarkupString` | It is just text | Use `MarkupString` only for your own HTML | Harmful HTML or scripts can run |
| HTML outside the braces of `@if` | Razor knows which lines belong to the `@if` | Put the HTML inside `{ }` | The HTML always shows |
| Missing `break;` in a `@switch` case | Cases stop by themselves | End every case with `break;` | A build error |
| Using an HTML comment for private notes | `<!-- -->` is hidden | Use `@* *@` | Anyone can read it with View source |

</div>

## Check Yourself

## Exercises

## What to Remember

- Razor mixes HTML and C#. `@` starts the C# part. `@@` shows a real `@`.
- `@code { }` holds variables and methods.
- `@name` is an implicit expression. `@( )` is explicit: use it for spaces and maths.
- `MarkupString` shows raw HTML. Use it only for HTML you wrote.
- `@if`, `@switch` and loops choose and repeat HTML.
- `@* *@` comments never reach the browser. `@using` brings in a namespace.

Next: **Components Basics**
