Lesson 3 of 10

Razor Syntax, C# Expressions, and Rendering Data

Use Razor syntax to combine HTML and C#, display variables, make decisions, and render collections.

Visual Studio 2026.NET 10Beginner friendly

Razor syntax lets you switch naturally between HTML and C#. You can display values, run conditions, loop through collections, and call methods directly from a component.

1. Create BasicsDemo.razor

Add a Razor component under Components/Pages named BasicsDemo.razor.

@page "/basics-demo"

<PageTitle>Razor Basics</PageTitle>

<h1>Razor Basics</h1>

<p>Student: @studentName</p>
<p>Course: @courseName</p>
<p>Current time: @DateTime.Now.ToShortTimeString()</p>

@if (score >= 50)
{
    <p>Result: Pass</p>
}
else
{
    <p>Result: Fail</p>
}

<h3>Modules</h3>
<ul>
    @foreach (var module in modules)
    {
        <li>@module</li>
    }
</ul>

@code {
    private string studentName = "Alice Tan";
    private string courseName = "Computer Science";
    private int score = 78;

    private List<string> modules = new()
    {
        "C# Programming",
        "Blazor",
        "Database Systems"
    };
}

2. Understand the Razor symbols

  • @variable renders a C# value.
  • @if runs conditional C# logic.
  • @foreach repeats markup for each item in a collection.
  • @code contains fields, properties, and methods for the component.

3. Render objects, not just strings

You can also create a model object inside the component:

@code {
    private Student student = new()
    {
        Name = "John Lee",
        Course = "Software Engineering"
    };

    private class Student
    {
        public string Name { get; set; } = "";
        public string Course { get; set; } = "";
    }
}

Then render @student.Name and @student.Course in the markup.

Try it yourself

Add a list of three scores and use foreach to display them. Then add an if statement that shows whether the student's main score is 80 or above.