Dynamic Rendering in Blazor Using Implicit and Explicit Expressions

Introduction

Blazor is famously known as component-based architecture. As we know, a component in Blazor is composed of HTML and C#. And for dynamic rendering, these two sections need to communicate effectively.

In this article, we will explore how dynamic rendering is achieved in Blazor using expressions. Blazor offers three types of expressions.

  1. Implicit expressions
  2. Explicit expressions
  3. Code blocks

Implicit expressions

Implicit expressions are used to render the value of a single variable or property directly within the HTML markup. They are denoted by a single @ symbol followed by the variable or property name.

Syntax

<p>@UserName</p>
@code 
{
   public string UserName { get; set; } = "John Doe";
}

Code snippet 1

Implicit expressions allow for direct binding of C# properties to HTML elements, as demonstrated in the example above.

 Implicit Expression

Image 1. Rendering with implicit expression

Integrating Implicit Expressions with HTML Element's Content

Implicit expressions can be directly used in HTML content. Consider the following example.

<p>Hello, @UserName! We're glad to have you here.</p>

Code snippet 2

In this snippet, @UserName is an implicit expression that dynamically renders the value of the UserName variable within the paragraph's text.

HTML Content

Image 2. Implicit expression combined with HTML content

Using Expressions as Attribute Values

Blazor has the capability to dynamically apply values to the attributes of HTML elements. Let's apply a style to a <p> tag using a class attribute, where the class name is loaded from C#.

<p class="@StyleForUserName">@UserName</p>
<style>
    .userNameStyle {
        font-size: 24px;
        color: darkblue;
    }
</style>
@code 
{
    public string UserName { get; set; } = "John Doe";
    public string StyleForUserName { get; set; } = "userNameStyle";
}

Code snippet 3

Let's say you have a style defined inside a <style> tag, as shown in the above code snippet.

In this example, we are applying this style to a paragraph <p> element. As we all know we need to specify a CSS class in order to assign a style. So here, @StyleForUserName is an implicit expression that dynamically assigns the CSS class to the <p> element based on the value of the StyleForUserName property in C#.

By creating a StyleForUserName property and assigning it the name of the style you wish to apply to the element, you can dynamically control the styling. In this example, I have assigned the CSS class name "userNameStyle".

Attribute Value

Image 3. Implicit expression used as an attribute value

Using Expressions in Style Property Values

You can use implicit expressions to dynamically set style property values. Consider the following example.

<p class="userEmail">@UserEmail</p>
<style>
    .userEmail {
        font-size: 18px;
        color: @UserEmailColor;
    }
</style>
@code {
    public string UserEmail { get; set; } = "[email protected]";
    public string UserEmailColor { get; set; } = "gray";
}

Code snippet 4

In the style .userEmail, there is a property named color. You can dynamically change the value of this property by assigning it to a C# variable. The @UserEmailColor expression dynamically sets the text color based on the value of the UserEmailColor C# property.

Color assignment

Image 4. Dynamic color assignment using an implicit expression

Using Expressions in Inline Styles

You can further utilize expressions by incorporating them directly into inline styles.

<p style="color:@InfoColor;">Feel free to explore and update your profile information.</p>
@code
{
   public string InfoColor { get; set; } = "purple";
}

Code snippet 5

In this example, @InfoColor is an expression that dynamically sets the color of the text inside the paragraph <p> element. The actual color value is determined by the C# property InfoColor.

 Inline style

Image 5. Inline style dynamic color assignment using an implicit expression

Using Expressions Inside JavaScript

Expressions can also be used with JavaScript.

<script>
    var userId = @UserId;
    console.log("User ID: " + userId);
</script>
@code 
{
    public int UserId { get; set; } = 12345;
}

Code snippet 6

The <script> tag contains JavaScript code that assigns the value of the C# variable @UserId to a JavaScript variable userId. This enables JavaScript to access and utilize the UserId value within the script.

Explicit Expressions in Razor

Explicit expressions enable more complex C# expressions within HTML markup. They are denoted by @( ) and can incorporate calculations, method calls, concatenations, etc.

Explicit expressions are beneficial for real-time rendering, as they update the UI dynamically when the underlying data changes with specified UI logic.

Syntax

<p>@("Hello, " + UserName)</p>

Code snippet 7

Modifying C# Properties Directly in HTML

Let's explore a practical use case by calculating and displaying the total cost of multiple units of a product.

<p>Total cost for 3 units: $@(ProductPrice * 3)</p>
@code {
    public decimal ProductPrice { get; set; } = 99.99m;
}

Code snippet 8

In this example, the expression @(ProductPrice * 3) multiplies the value of ProductPrice directly in HTML. Given that ProductPrice is set to 99.99, the total cost is calculated as 99.99 * 3, resulting in $299.97.

 C# Properties

Image 6. Modifying C# Properties Directly in HTML

Formatting Strings

You can perform complex operations such as formatting strings.

    <p>@($"Buy 2 get 1 free: Pay for 2 units: {ProductPrice * 2:N2}")</p>

Code snippet 9

In the above example, N2 at the end of the string formats the number with thousands of separators and 2 decimal places. You can adjust the format as needed.

Strings

Image 7. Formatting Strings

    <p>@($"Buy 2 get 1 free: Pay for 2 units: {ProductPrice * 2:N5}")</p>

Code snippet 10

Now the string will display the calculated value with up to 5 decimal places.

 Formatting Strings

Image 8. Formatting Strings

Using Booleans to Our Advantage

Booleans can be used to toggle various states in elements, such as dynamically applying CSS classes in this case.

<div class="productCard @(IsHighlighted ? "highlight" : "normal")">
    <style>
        .highlight {
            background-color: #d4e6f1;
        }
        .normal {
            background-color: white;
        }
    </style>
</div>
@code {
    public bool IsHighlighted { get; set; } = true;
}

Code snippet 11

In this example, the <div> element uses a conditional ternary operator within the class attribute to apply different CSS classes (highlight or normal) based on the value of the IsHighlighted property:

If IsHighlighted is true, the highlight class is applied, resulting in a light blue background.

Boolean

Image 9. Toggling with boolean

If IsHighlighted is false, the normal class is applied, resulting in a white background.

Toggling

Image 10. Toggling with boolean

You'll quickly realize that whether using implicit or explicit expressions, they are often limited to simple expressions within an element. However, Blazor provides a way to embed entire blocks of C# code directly into HTML using code blocks @{  }.

   @{
    var discountedPrice = ProductPrice * (1 - (decimal)(DiscountPercentage / 100));
    var savings = ProductPrice * (decimal)(DiscountPercentage / 100);
    var stockStatus = IsOutOfStock ? "Out of Stock" : "In Stock";
}
<div>
    <p>Discounted Price: $@(discountedPrice)</p>
    <p class="discountMessage">@($"You save {savings:C} with a {DiscountPercentage}% discount!")</p>
    <p>@stockStatus</p>
</div>
@code {
    public decimal ProductPrice { get; set; } = 99.99m;
    public double DiscountPercentage { get; set; } = 10;
    public bool IsOutOfStock { get; set; } = false;
}

Code snippet 12

In this example, the C# code block calculates and displays a discounted price, savings, and stock status of a product directly within the HTML structure. This approach allows for more complex logic and dynamic content generation directly within the UI piece of components.

Code Blocks

Image 11. Using code blocks { }

We've covered a lot. I'm sure you'll appreciate seeing examples of both implicit and explicit expressions. For your reference, let me provide the complete source code for implicit expression followed by explicit expression.

@page "/implicit"
<style>
    .profileCard {
        border: 1px solid #ccc;
        padding: 20px;
        margin: 20px;
        border-radius: 10px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    .userNameStyle {
        font-size: 24px;
        color: darkblue;
        margin-bottom: 5px;
    }
    .userEmail {
        font-size: 18px;
        color: @UserEmailColor;
        margin-bottom: 10px;
    }
    .welcomeMessage {
        font-size: 20px;
        color: @WelcomeTextColor;
        margin-bottom: 10px;
    }
</style>
<h1>Welcome to Your Profile Page</h1>
<div class="profileCard">
    <p class="@StyleForUserName">@UserName, @UserAge</p>
    <p class="userEmail">@UserEmail</p>
    <p class="welcomeMessage">Hello, @UserName! We're glad to have you here.</p>
</div>
<p style="color:@InfoColor;">Feel free to explore and update your profile information.</p>
<script>
    var userId = @UserId;
    console.log("User ID: " + userId);
</script>
@code {
    public string UserName { get; set; } = "John Doe";
    public string StyleForUserName { get; set; } = "userNameStyle";

    public string UserEmail { get; set; } = "[email protected]";
    public int UserAge { get; set; } = 25;
    public int UserId { get; set; } = 12345;
    public string UserEmailColor { get; set; } = "gray";
    public string WelcomeTextColor { get; set; } = "green";
    public string InfoColor { get; set; } = "purple";
}

Code snippet 13: Implicit expression

Output

Image 12. Output of code snippet 13, Implicit expression

Here is the source code for explicit expressions.

@page "/explicit"
<h1>Product Details</h1>
@{
    var discountedPrice = ProductPrice * (1 - (decimal)(DiscountPercentage / 100));
    var savings = ProductPrice * (decimal)(DiscountPercentage / 100);
    var stockStatus = IsOutOfStock ? "Out of Stock" : "In Stock";
}
<div class="productCard @(IsHighlighted ? "highlight" : "normal")">
    <p class="productName">@ProductName</p>
    <p class="productPrice">Price: $@(ProductPrice)</p>
    <p>Discounted Price: $@(discountedPrice)</p>
    <p class="discountMessage">@($"You save {savings:C} with a {DiscountPercentage}% discount!")</p>
    <p class="@("outOfStock")">@stockStatus</p>
</div>
<p>Total cost for 3 units: $@(ProductPrice * 3)</p>
<p>@($"Buy 2 get 1 free: Pay for 2 units: {ProductPrice * 2:N5}")</p>
<style>
    .productCard {
        border: 1px solid #ccc;
        padding: 20px;
        margin: 20px;
        border-radius: 10px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    .productName {
        font-size: 24px;
        color: @ProductNameColor;
        margin-bottom: 5px;
    }
    .productPrice {
        font-size: 18px;
        color: @ProductPriceColor;
        margin-bottom: 10px;
    }
    .discountMessage {
        font-size: 16px;
        color: @DiscountMessageColor;
    }
    .highlight {
        background-color: #d4e6f1;
    }
    .normal {
        background-color: white;
    }
    .outOfStock {
        color: red;
        font-weight: bold;
    }
</style>
<script>
    var productId = @ProductId;
    console.log("Product ID: " + productId);
</script>
@code {
    public string ProductName { get; set; } = "Wireless Headphones";
    public decimal ProductPrice { get; set; } = 99.99m;
    public int ProductId { get; set; } = 67890;
    public double DiscountPercentage { get; set; } = 10;
    public string ProductNameColor { get; set; } = "darkblue";
    public string ProductPriceColor { get; set; } = "green";
    public string DiscountMessageColor { get; set; } = "red";
    public bool IsHighlighted { get; set; } = true;
    public bool IsOutOfStock { get; set; } = false;
}

Code snippet 14: Explicit expression

Explicit Expression

Image 13. Output of code snippet 14, Explicit expression

Conclusion

In this article, we've learned about both implicit and explicit expressions, as well as the use of code blocks. Blazor, with its component-based architecture blending HTML and C#, enables dynamic content generation directly within UI components.

  1. Implicit Expressions: Used for straightforward binding of C# properties to HTML elements.
  2. Explicit Expressions: Enable more complex C# logic within HTML, ideal for real-time updates based on data changes and for performing calculations or formatting strings dynamically.
  3. Code Blocks: Provide the flexibility to embed entire C# code segments within HTML.

These techniques allow you to leverage Blazor's capabilities in creating responsive and interactive web applications.


Similar Articles