Course contentsShow
← C#
Lesson 1318 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Conditional CSS Class Binding

Apply dynamic styling to elements based on server-side logic states.

Mastering Conditional CSS Class Binding

In this lesson, you will learn how to dynamically apply CSS classes to your HTML elements based on the current state of your C# backend logic.

When building dynamic UIs, you often need to change the appearance of an element—such as turning a status indicator green when a task is completed or highlighting an input field that failed validation. Instead of manipulating the DOM with heavy JavaScript, Razor allows you to compute the necessary class strings directly within your markup using C# expressions.

The Logic Behind the Binding

The core idea is to embed a C# expression within the class attribute of your HTML tag. Since the class attribute is just a string, you can use a ternary operator to decide which class to inject based on a boolean condition.

Consider a scenario where you are displaying a user's connection status:

<div class="@(IsOnline ? "status-online" : "status-offline")">
    Status: @(IsOnline ? "Active" : "Disconnected")
</div>

In this example, the @(...) syntax instructs Razor to evaluate the C# logic first. If IsOnline is true, the rendered HTML becomes <div class="status-online">. If false, it becomes <div class="status-offline">.

Handling Multiple Classes

Sometimes you need to apply a base class that is always present, combined with a conditional modifier. You can handle this by concatenating the strings or using a simple string interpolation:

<button class="btn @(IsEnabled ? "btn-primary" : "btn-disabled")">
    Submit
</button>

By keeping your styling logic in C#, you ensure that your UI stays perfectly synchronized with your backend state. This approach is clean, type-safe, and avoids the "spaghetti code" that often arises when trying to manage UI states through external scripts.

Always remember that the C# expression inside the parentheses must return a string. By using ternary operators (condition ? trueResult : falseResult), you keep your markup concise and readable while maintaining full control over your component's aesthetic state.

Key Takeaway: Use C# ternary expressions inside the class attribute to inject dynamic styles based on server-side model states.