Lesson 4 of 10

Events and Two-Way Data Binding

Handle button clicks, capture user input, and use @bind to create an interactive Razor component.

Visual Studio 2026.NET 10Beginner friendly

Blazor becomes interactive when components respond to browser events. You can handle clicks, read text input, and keep C# fields synchronized with form controls.

Interactivity note

If you created the project with global Interactive Server mode, the examples below work as written. If you chose per-page interactivity, add @rendermode InteractiveServer near the top of the page.

1. Create InteractiveDemo.razor

@page "/interactive-demo"

<PageTitle>Interactive Demo</PageTitle>

<h1>Interactive Demo</h1>

<p>Current count: @count</p>
<button class="btn btn-primary" @onclick="IncreaseCount">Increase</button>
<button class="btn btn-secondary" @onclick="ResetCount">Reset</button>

<hr />

<label>Your name:</label>
<input class="form-control" @bind="name" />

<p>Hello, @name!</p>

@code {
    private int count = 0;
    private string name = "Student";

    private void IncreaseCount()
    {
        count++;
    }

    private void ResetCount()
    {
        count = 0;
    }
}

2. Event handling

The @onclick attribute connects a browser click event to a C# method. When the method changes component state, Blazor renders the necessary UI updates.

3. Two-way binding

The @bind directive keeps the input value and the C# field synchronized. Type into the input and watch the greeting update.

4. Bind to other input types

<input type="number" @bind="age" />
<input type="checkbox" @bind="isActive" />

@code {
    private int age = 20;
    private bool isActive = true;
}

Try it yourself

Add a Decrease button that subtracts one from the counter, but do not allow the count to go below zero.