Blazor Server – dev-docs

Common patterns and examples for building interactive Blazor Server apps.

→ Official Blazor Documentation

Render Mode

<component type="typeof(App)" render-mode="InteractiveServer" />

Use in _Host.cshtml for Blazor Server. Enables SignalR-based interaction.

Lifecycle Hooks

@code {
    protected override void OnInitialized()
    {
        // Runs when the component is initialized
    }

    protected override async Task OnInitializedAsync()
    {
        // Async init logic
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // Runs once after first render
        }
    }
}

Two-Way Data Binding

<input @bind="username" />

@code {
    private string username = string.Empty;
}

Input Events: @oninput and @onchange

<input @oninput="HandleInput" placeholder="Type something..." />
<input @onchange="HandleChange" placeholder="Change triggers on blur" />

@code {
    private string currentValue = "";

    private void HandleInput(ChangeEventArgs e)
    {
        var value = e.Value?.ToString();
        currentValue = value ?? "";
    }

    private void HandleChange(ChangeEventArgs e)
    {
        var value = e.Value?.ToString();
        Console.WriteLine($"Changed to: {value}");
    }
}

Parse string to int (with validation)

<input @oninput="HandleIntInput" placeholder="Enter number" />

@code {
    private string inputValue = "";
    private int parsedValue = 0;

    private void HandleIntInput(ChangeEventArgs e)
    {
        inputValue = e.Value?.ToString() ?? "";
        if (int.TryParse(inputValue, out int result))
        {
            parsedValue = result;
        }
    }
}

Click Events

<button @onclick="SayHello">Click me</button>

@code {
    private void SayHello()
    {
        Console.WriteLine("Hello from Blazor Server!");
    }
}

Events With Parameters

<button @onclick="() => GreetUser("Alice")">Greet Alice</button>

@code {
    private void GreetUser(string name)
    {
        Console.WriteLine($"Hello, {name}!");
    }
}

Search and Filter a List

<input @bind="SearchTerm" placeholder="Search..." />

<ul>
    @foreach (var item in FilteredItems)
    {
        <li>@item</li>
    }
</ul>

@code {
    private string SearchTerm = "";

    private List<string> Items = new()
    {
        "Blazor",
        "C#",
        "SignalR",
        "WebAssembly",
        "ASP.NET Core"
    };

    private IEnumerable<string> FilteredItems =>
        string.IsNullOrWhiteSpace(SearchTerm)
            ? Items
            : Items.Where(i =>
                i.Contains(SearchTerm, StringComparison.OrdinalIgnoreCase));
}

Authorization

@attribute [Authorize]
@attribute [Authorize(Roles = "Admin")]

<AuthorizeView>
    <Authorized>
        <p>Welcome, user!</p>
    </Authorized>
    <NotAuthorized>
        <p>Please sign in.</p>
    </NotAuthorized>
</AuthorizeView>

Blazor EditForm with All Input Types

<EditForm Model="@dummyModel" OnValidSubmit="@HandleSubmit">
    <DataAnnotationsValidator />

    @* --- InputText for normal text entries --- *@
    <div class="mb-3">
        <label for="name" class="form-label">Name (InputText)</label>
        <InputText id="name" @bind-Value="dummyModel.Name" class="form-control" />
        <ValidationMessage For="() => dummyModel.Name" />
    </div>

    @* --- InputNumber for numbers (int, decimal, etc.) --- *@
    <div class="mb-3">
        <label for="amount" class="form-label">Amount (InputNumber)</label>
        <InputNumber id="amount" @bind-Value="dummyModel.Amount" class="form-control" />
        <ValidationMessage For="() => dummyModel.Amount" />
    </div>
    
    @* --- InputDate for date selection --- *@
    <div class="mb-3">
        <label for="startDate" class="form-label">Start Date (InputDate)</label>
        <InputDate id="startDate" @bind-Value="dummyModel.StartDate" class="form-control" />
        <ValidationMessage For="() => dummyModel.StartDate" />
    </div>

    @* --- InputSelect for a dropdown selection (here with an Enum) --- *@
    <div class="mb-3">
        <label for="category" class="form-label">Category (InputSelect)</label>
        <InputSelect id="category" @bind-Value="dummyModel.Category" class="form-select">
            <option value="">Please select...</option>
            @foreach (var cat in Enum.GetValues<DummyCategoryEnum>())
            {
                <option value="@cat">@cat</option>
            }
        </InputSelect>
        <ValidationMessage For="() => dummyModel.Category" />
    </div>

    @* --- InputTextArea for multi-line text entries --- *@
    <div class="mb-3">
        <label for="description" class="form-label">Description (InputTextArea)</label>
        <InputTextArea id="description" @bind-Value="dummyModel.Description" class="form-control" rows="3" />
        <ValidationMessage For="() => dummyModel.Description" />
    </div>
    
    @* --- InputCheckbox for Yes/No values --- *@
    <div class="form-check mb-3">
        <InputCheckbox id="isActive" @bind-Value="dummyModel.IsActive" class="form-check-input" />
        <label for="isActive" class="form-check-label">Active (InputCheckbox)</label>
    </div>

    @* --- Buttons --- *@
    <div class="mt-3">
        <button type="submit" class="btn btn-primary">Save</button>
        <button type="button" class="btn btn-secondary">Cancel</button>
    </div>
</EditForm>