Isaac.

Blazor Server Applications

Build interactive web apps with C# using Blazor Server.

By EMEPublished: February 20, 2025
blazorcsharpdotnetinteractiveweb

A Simple Analogy

Blazor Server is like controlling a web page from the server. Instead of JavaScript on the client, you write C# on the server and changes appear instantly on the browser.


What Is Blazor Server?

Blazor Server runs your .NET application on the server, with UI updates sent over WebSocket in real-time. No JavaScript needed—pure C#.


Why Use Blazor Server?

  • C# in browser: Write C# instead of JavaScript
  • Real-time updates: WebSocket for instant communication
  • Full .NET access: Use any .NET library
  • Server-side logic: Business logic stays on server
  • Easier learning: If you know C#, you can build web UIs

Basic Component

// Pages/Counter.razor
@page "/counter"

<h1>Counter</h1>
<p>Current count: @count</p>
<button class="btn btn-primary" @onclick="IncrementCount">
    Click me
</button>

@code {
    private int count = 0;

    private void IncrementCount()
    {
        count++;
    }
}

Data Binding

@page "/form"

<h1>Order Form</h1>

<input type="text" @bind="order.CustomerName" />
<input type="number" @bind="order.Amount" />
<textarea @bind="order.Notes"></textarea>

<button @onclick="SubmitOrder">Submit</button>

@if (submitted)
{
    <p>Order submitted successfully!</p>
}

@code {
    private Order order = new();
    private bool submitted = false;

    private async Task SubmitOrder()
    {
        await orderService.CreateAsync(order);
        submitted = true;
    }
}

Dependency Injection

// Program.cs
builder.Services.AddScoped<IOrderService, OrderService>();

// Component
@inject IOrderService OrderService

@page "/orders"

<h1>Orders</h1>
<ul>
@foreach (var order in orders)
{
    <li>@order.Id - @order.Total</li>
}
</ul>

@code {
    private List<Order> orders = new();

    protected override async Task OnInitializedAsync()
    {
        orders = await OrderService.GetAllAsync();
    }
}

Event Handling

<button @onclick="HandleClick">Click me</button>
<button @onclick="@(e => HandleClickAsync(123))">Click with param</button>

@code {
    private void HandleClick()
    {
        // Handle click
    }

    private async Task HandleClickAsync(int id)
    {
        await someService.ProcessAsync(id);
    }
}

Best Practices

  1. Keep components small: Easy to test and reuse
  2. Use child components: Compose UI from pieces
  3. Handle async: Use OnInitializedAsync
  4. Optimize rendering: Prevent unnecessary updates
  5. Error handling: Validate user input

Related Concepts

  • Blazor WebAssembly (client-side)
  • Component lifecycle (OnInitialized, OnParametersSet)
  • Cascading parameters
  • Event callbacks

Summary

Blazor Server brings C# to web development with real-time updates via WebSocket. Perfect for interactive UIs where you can leverage existing .NET libraries.