skip to content

In a Razor view (.cshtml), how does the @ character switch from HTML to C#, and how do @if and @foreach render markup?

level: juniorimportance: must knowfreq 62%

answer

  1. HTML is the default language
  2. one character starts C#
  3. a tag inside braces is markup again
  4. else follows the brace bare

basics

~20 s

A Razor view is HTML until an @ starts C#: @value writes an HTML-encoded value, and @if or @foreach run C# whose braces may hold HTML tags, which render as markup each time that branch or pass runs.

solid answer

~40 s

In a Razor view the default language is HTML, so markup goes out as written until `@` switches to C#. An implicit expression such as `@customerName` or `@line.Sku` evaluates and writes its value, HTML-encoded. Control structures start with `@` too: `@if`, `@foreach`, `@for`, `@while`, `@switch` and `@try`. Inside their braces you are back in C#, but a line that starts with an HTML tag switches to markup until that element closes, so `<li>@line.Sku</li>` inside `@foreach` renders one `<li>` per item. `else` and `else if` follow the closing brace with no `@`, and a `@{ }` code block runs statements without writing anything itself.

code

razor · 18 lines
razor
@{
    var customerName = "Ana Lee";
    var lines = new[] { new Line("A-1", 2, 9.50m), new Line("B-2", 1, 20m) };
}
<h1>Thank you, @customerName</h1>
@if (lines.Length == 0)
{
    <p>Your order is empty.</p>
}
else
{
    <ul>
    @foreach (var line in lines)
    {
        <li>@line.Sku x @line.Qty</li>
    }
    </ul>
}

go deeper

for a junior

Recall that HTML is the default, @ switches to C#, @value writes an encoded value, and @if or @foreach wrap markup that renders per branch or per pass; else has no @.

for a middle

Explain how the parser flips back to markup when a line inside braces starts with a tag, and why a @{ } block runs statements but writes nothing on its own.

for a senior

Show you can read a view and predict its output, including which values are encoded, and keep control flow light so views stay readable and logic stays in testable C#.

for a principal

Frame Razor's control structures as a readability tool: they are fine for presentation branching and loops, but business decisions belong in code that is tested outside the view.

## HTML is the default language A Razor file such as an MVC view or a Razor Page (`.cshtml`) is compiled into a C# class. Everything that is plain HTML becomes a literal that is written to the response **exactly as typed**. Razor only does something different when it meets the **transition character** `@`. That single character is the whole switch between the two languages: before it the parser is reading HTML, after it the parser is reading C#. In markup, `@` most often starts one of three things (escapes such as `@@` and comments such as `@* *@` are separate cases): - an **expression** that is evaluated and written to the page (`@customerName`); - a **code block** `@{ ... }` holding C# statements that run but write nothing by themselves; - a **control structure** or **directive** whose name is a reserved keyword (`@if`, `@foreach`, `@using`, `@functions` and so on). ## Implicit expressions: `@` plus a value The everyday form is the **implicit expression**: `@` followed by an identifier and any member access, method call or indexer chained to it, such as `@customerName`, `@line.Sku` or `@lines[0].Sku`. Razor evaluates it and writes the result. Two details matter even at the start: 1. The value is **HTML-encoded** before it is written, so a name containing `<b>` shows the characters rather than making text bold. 2. The expression ends at the first space or character that cannot continue it, so `@lines.Length * 2` writes the length followed by the literal text ` * 2`. Arithmetic, generics and similar cases need the explicit form `@( ... )`. ## Control structures: C# that wraps markup Control structures are C# statements prefixed with `@`. Razor supports `@if` with `else if` and `else`, `@switch`, `@for`, `@foreach`, `@while`, `@do while`, `@try` with `catch` and `finally`, `@lock`, and the compound `@using (...) { }` statement. | Construct | Starts with | Writes output by itself? | |---|---|---| | Implicit expression | `@name` | Yes, the encoded value | | Explicit expression | `@( ... )` | Yes, the encoded value | | Code block | `@{ ... }` | No | | Control structure | `@if`, `@foreach`, ... | Only the markup and expressions inside its braces | Only the first keyword needs the `@`. The `else` and `else if` that follow an `@if` block's closing brace are written bare; writing `@else` makes the build fail, because `else` cannot start a statement of its own. ## Switching back to markup inside the braces Inside the braces of a control structure or code block the parser is in C#. When a line starts with an HTML tag, Razor switches back to markup automatically and stays there until that element closes. Inside the element, `@` starts C# again. That nesting is what makes loops read naturally: - `@foreach (var line in lines) { <li>@line.Sku</li> }` writes one `<li>` per item; - `@if (lines.Length == 0) { <p>Your order is empty.</p> }` writes the paragraph only when the condition holds; - a `case` inside `@switch` can hold markup followed by `break;`. Text that is **not** wrapped in a tag is read as C# inside braces, which is why plain text there needs the `@:` or `<text>` transition (a separate topic). ## A worked example: an order-confirmation view An order-confirmation view prints the customer's name and one line per order item. The code block declares the data, an implicit expression prints the name, `@if` with a bare `else` handles the empty order, and `@foreach` repeats the `<li>` element. Every `@` value in it is HTML-encoded on the way out. It helps to picture what the compiler produces. Razor turns the file into one render method: each run of HTML becomes a `WriteLiteral("...")` call, each expression becomes a `Write(value)` call that encodes, and each control structure becomes the ordinary C# statement it looks like, with those write calls inside its body. Read that way, the output is predictable: - the `<h1>` literal is written once, with the encoded name in the middle; - the `@if` condition is evaluated once, and only one branch's literals run; - the `<li>` literal and its `Write(line.Sku)` call sit inside the `foreach` body, so they run once per item. ## Common mistakes - Expecting a `@{ }` block to print the value of its last line: a code block writes nothing unless it contains markup or an expression. - Prefixing `else` with `@`. - Assuming `@` output is raw: strings are encoded unless you deliberately opt out with `Html.Raw`. - Putting `@` in front of every statement inside a block: once you are in C#, plain C# statements need no prefix.

  • Can a Razor view use @switch and @try as well as @if and @foreach?
    Yes. Razor supports `@switch` with `case` labels that hold markup and end with `break;`, `@for`, `@while`, `@do while`, `@try` with `catch` and `finally`, `@lock`, and the compound `@using (...) { }` statement. All of them follow the same rule: the keyword carries the `@`, the braces hold C#, and a line that starts with a tag renders as markup.
  • Inside an @foreach body in a Razor view, how do you print words that have no HTML tag around them?
    Inside the braces Razor reads C#, so bare words such as `Item:` are parsed as code and break the build. Either wrap the text in an element, use `@:` to render the rest of that line as markup, or wrap it in `<text>...</text>`, which renders only its contents. Expressions after `@:` or inside `<text>` are still evaluated and encoded.

A Razor view is like a printed form with blanks: the printed text goes out as it is, each @ marks a blank filled in with a computed value, and an @foreach is the instruction to repeat a row of the form once per item.

  • Every keyword in a Razor control block needs its own @, including else.
  • A @{ } code block writes the value of its last line to the page.
  • Markup inside @foreach braces is printed once, not once per item.
  • Razor writes @ values raw, exactly as the string holds them.
  • Each C# statement inside a code block must start with @.