In this lesson, you will learn how to seamlessly weave C# logic directly into your HTML markup using Razor syntax to render dynamic content based on state.
Dynamic Rendering with Razor
When building modern frontends with Blazor, you often need the UI to react to data—such as hiding an "Admin Panel" if the user isn't logged in, or listing items from a database. Instead of writing complex JavaScript, you use the @ symbol to tell the Razor engine: "The following code is C#, not HTML."
Conditional Rendering
To show or hide elements, we use standard C# if statements wrapped in the @ syntax. The Razor engine treats everything inside the braces as C# and everything outside as static HTML.
@if (user.IsAuthenticated)
{
<p>Welcome back, @user.Username!</p>
}
else
{
<button>Please Log In</button>
}
Iterative List Generation
When you have a collection of data, such as a list of product objects or user notifications, you use a foreach loop to generate markup for each entry. This creates a clean, declarative bridge between your backend data and your frontend display.
<ul>
@foreach (var task in todoList)
{
<li>
<input type="checkbox" checked="@task.IsDone" />
@task.Title
</li>
}
</ul>
The "At" (@) Rule
It is important to remember that Razor is smart enough to switch contexts. When you open a code block with @if or @foreach, you enter C# mode. When you place an HTML tag like <li> inside those braces, the engine automatically switches back to HTML mode to render the content, then returns to C# mode to continue the loop. This allows you to build complex, nested interfaces without breaking the flow of your markup.
By embedding logic directly into the view, you maintain a "single source of truth" for your UI state, ensuring your frontend reflects your C# data models in real-time.
Key Takeaway: Use the @ symbol to toggle between HTML and C# contexts, allowing you to use standard conditional and iterative statements directly within your markup to drive dynamic user interfaces.