Skip to content

Introduction to Blazor

What is Blazor?

Blazor is a framework for building interactive web UIs using C#:

  • Write C# instead of JavaScript
  • Build reusable UI components
  • Share code between client and server

Types of Blazor

  1. Blazor Server

    • Runs on server
    • Updates UI over SignalR connection
    • Smaller download size
    • Works on older browsers
  2. Blazor WebAssembly

    • Runs entirely in browser
    • Offline capable
    • Direct access to browser APIs
    • Larger initial download
  3. Blazor Hybrid

    • Combines native and web UI
    • Share code between platforms
    • Access native features

Create Project

To create a new Blazor project:

bash
dotnet new blazorserver -n MyBlazorApp   # For Blazor Server
dotnet new blazorwasm -n MyBlazorApp     # For Blazor WebAssembly

Components in Blazor

Components are the building blocks of Blazor applications:

razor
@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

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

@code {
    private int currentCount = 0;

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

Lifecycle of Components

Components have the following lifecycle methods:

  • OnInitialized / OnInitializedAsync
  • OnParametersSet / OnParametersSetAsync
  • OnAfterRender / OnAfterRenderAsync
  • IDisposable.Dispose

Data Binding

Blazor supports both one-way and two-way data binding:

razor
<!-- One-way binding -->
<p>@message</p>

<!-- Two-way binding -->
<input @bind="message" />
<input @bind="message" @bind:event="oninput" />

Event Handling

Handle DOM events using C# methods:

razor
<button @onclick="HandleClick">Click Me</button>
<input @onchange="HandleChange" />

@code {
    private void HandleClick() { }
    private void HandleChange(ChangeEventArgs e) { }
}

Conditional Rendering and Loops

razor
@if (isVisible)
{
    <p>Visible content</p>
}

@foreach (var item in items)
{
    <li>@item.Name</li>
}

Common Directives in Blazor

  • @page - Specifies routing template
  • @inject - Dependency injection
  • @layout - Specifies layout component
  • @using - Import namespaces
  • @implements - Implement interfaces
  • @inherits - Specify base class

Routing in Blazor

razor
@page "/counter"
@page "/counter/{currentCount:int}"

@code {
    [Parameter]
    public int CurrentCount { get; set; }
}

Dependency Injection

razor
@inject ILogger<Counter> Logger
@inject NavigationManager NavigationManager

@code {
    protected override void OnInitialized()
    {
        Logger.LogInformation("Component initialized");
    }
}

Forms and Validation

razor
<EditForm Model="@model" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText @bind-Value="model.Name" />
    <ValidationMessage For="@(() => model.Name)" />
    
    <button type="submit">Submit</button>
</EditForm>

Reusable Components

Create reusable components by accepting parameters:

razor
@code {
    [Parameter]
    public string Title { get; set; }

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

Blazor and JavaScript

Interact with JavaScript using JSRuntime:

razor
@inject IJSRuntime JS

@code {
    private async Task CallJavaScript()
    {
        await JS.InvokeVoidAsync("console.log", "Hello from Blazor");
    }
}

Deploying Blazor Applications

  • Blazor Server apps deploy to ASP.NET Core servers
  • Blazor WebAssembly apps can be deployed to static hosting
  • Configure proper compression and caching
  • Consider CDN for static assets

Debugging and Optimization

  • Use browser developer tools
  • Enable source maps for debugging
  • Optimize component rendering
  • Implement lazy loading
  • Use proper state management
  • Profile performance bottlenecks