C# ASP.NET offers a way to build highly interactive web UIs using C# and .NET. Blazor helps us to make the app interactive via different modes such as

  • Static Web Apps
  • Interactive Server ( Blazor Server )
  • WASM (Web Assembly)

A Blazor app is based on Components with .razor extention. It is a combination of C# and HTML.

Example:

// Counter.razor
@page "/counter"
@rendermode InterativeServer

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}
// PageTitle.razor

<h3>@ChildContent</h3>

@code {
    [Parameter]
    public RenderFragment ChildContent { get; set; }
}

In the above example, <PageTitle> is another component. @code block is used to write the C# code. This block will render a counter and a button to increment the counter.

Alternatively we can use Counter.razor.cs to write the C# code.

// Counter.razor.cs

public partial class Counter
{
    private int currentCount = 0;

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

Blazor supports two-way data binding, event handling, and dependency injection. It also supports routing, forms, and validation. Blazor can be hosted in different ways.

  • Blazor Server: The app runs on the server and the UI updates are sent to the client over a SignalR connection.
  • Blazor WebAssembly: The app runs on the client using WebAssembly and the .NET runtime is downloaded to the client.
  • Blazor Hybrid: The app runs on the server and the UI updates are sent to the client over a SignalR connection. The client runs on WebAssembly.

Interactive Server

sequenceDiagram
    participant User
    Client ->> Server: Request
    Server ->> Client: Html response
    Client --> Server: SignalR
    User ->> Client: Interaction
    Client ->> Server: Request
    Server ->> Client: Response

WASM

sequenceDiagram
    participant User
    Client ->> Server: Request
    Server ->> Client: Html response and WASM
    User ->> Client: Interaction