Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 41 ยท Components and Razor Syntax

Conditionals and Loops in Razor

Render dynamic Blazor UI with @if, @else, @switch, @foreach and @for: show loading and empty states, build lists and tables, use CSS classes conditionally, and avoid closure bugs in loops.

Real pages are rarely static. A list shows one row per item, a spinner appears while data loads, an error message shows only when something fails. Razor handles this with ordinary C# control flow written right inside the markup: @if, @switch, @foreach and @for. If you know C#, you already know the syntax; the only new part is how markup and code mix.

@if, else if and else

HTML
@if (user is null)
{
    <p>Please sign in.</p>
}
else if (user.IsAdmin)
{
    <p>Welcome back, administrator @user.Name.</p>
}
else
{
    <p>Hello, @user.Name.</p>
}

The braces are required, and the @ is only needed in front of the if itself. Inside the braces you are in markup mode: write HTML, and use @ for expressions. For a single optional element, an @if block with no else is perfectly fine:

HTML
@if (items.Count > 0)
{
    <span class="badge">@items.Count</span>
}

For a tiny choice inside an attribute or a sentence, use the ternary operator in an explicit expression:

HTML
<p class="@(isError ? "text-danger" : "text-success")">@message</p>
<button disabled="@(!canSave)">Save</button>

switch

HTML
@switch (order.Status)
{
    case OrderStatus.Pending:
        <span class="badge bg-warning">Pending</span>
        break;
    case OrderStatus.Shipped:
        <span class="badge bg-info">Shipped</span>
        break;
    default:
        <span class="badge bg-secondary">@order.Status</span>
        break;
}

When there are many cases, consider a helper method in @code that returns a CSS class or label, and keep the markup readable.

foreach

@foreach renders markup once per item:

HTML
<ul>
    @foreach (var product in products)
    {
        <li @key="product.Id">@product.Name: @product.Price.ToString("C")</li>
    }
</ul>

Add @key when items can be added, removed or reordered, as explained in How Blazor Renders. Tables work the same way:

HTML
<table>
    <thead><tr><th>Name</th><th>Qty</th></tr></thead>
    <tbody>
        @foreach (var line in order.Lines)
        {
            <tr><td>@line.Name</td><td>@line.Quantity</td></tr>
        }
    </tbody>
</table>

The closure trap in for loops

A classic bug with @for and event handlers: the loop variable is shared, so every button ends up using the final value.

HTML
@* Wrong: i is captured by reference and equals items.Count after the loop *@
@for (int i = 0; i < items.Count; i++)
{
    <button @onclick="() => Remove(i)">Remove</button>
}

@* Right: copy into a local variable inside the loop *@
@for (int i = 0; i < items.Count; i++)
{
    var index = i;
    <button @onclick="() => Remove(index)">Remove</button>
}

foreach does not have this problem in modern C#, because each iteration gets a fresh variable. Prefer @foreach (var item in items) and pass the item itself: @onclick="() => Remove(item)".

Loading, empty and error states

A good list component handles all four situations: loading, error, empty and data.

HTML
@if (loading)
{
    <p>Loading...</p>
}
else if (error is not null)
{
    <p class="text-danger">@error</p>
}
else if (items.Count == 0)
{
    <p>No items yet. Add the first one!</p>
}
else
{
    <ul>
        @foreach (var item in items)
        {
            <li>@item</li>
        }
    </ul>
}

Handling empty and loading explicitly is a hallmark of polished UI and prevents flashes of an empty table before data arrives.

Runnable stand-in: the same logic in C#

Blazor's loops and conditions are C# statements, so here is a runnable version that builds the same markup as a string. It also demonstrates the closure trap with real C#: a list of actions that capture the loop variable.

C# Stand-in: control flow and the closure trap

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.

The first three lines show one list component producing three different states; the last two blocks show why the copy var index = i; matters in @for loops with handlers.

Other ways to draw lists

  • Helper methods. @RenderRow(item) calls a method returning a RenderFragment, handy for markup shared within one component.
  • Child components. Make <ProductRow Product="p" /> for each item; each gets its own state and renders independently.
  • <Virtualize>. For thousands of rows, <Virtualize Items="rows" Context="row"> renders only the visible ones.
  • LINQ in @code. Filter and sort in a property or method, then loop over the result, instead of putting heavy LINQ in the markup: @foreach (var p in VisibleProducts).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the right way to show an element only when a condition is true?

    Razor uses plain C# @if blocks with braces.
  2. 2. Why does @onclick="() => Remove(i)" in a for loop often remove the wrong item?

    Copy the variable into a local inside the loop, or use foreach.
  3. 3. What does a polished list component handle besides showing the data?

    Explicit loading, error and empty states avoid blank or misleading screens.
  4. 4. Which is best for rendering 50,000 rows?

    Virtualize renders only the rows currently visible.

Summary

  • @if, @else, @switch, @foreach and @for are plain C# mixed with markup.
  • Use the ternary operator for small choices in attributes and text.
  • Use @key on repeated elements that can move, and copy for loop variables before capturing them.
  • Handle loading, error and empty states explicitly.
  • For very long lists, use <Virtualize>.

Next: Event Handling