Course contentsShow
← C#
Lesson 1324 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Data Binding and Event Handling

Synchronize UI elements with C# properties using two-way and one-way data binding.

In this lesson, you will learn how to synchronize your C# component state with the user interface using Blazor’s declarative binding and event handling systems.

The Mechanics of Data Binding

In Blazor, data binding is the bridge between your C# properties and your HTML elements. We use the @bind directive to create a seamless connection.

  • One-Way Binding: This is used to display data. When you write <h1>@UserName</h1>, the UI renders the value of the UserName property. If the property changes in C#, the UI updates.
  • Two-Way Binding: This is used for inputs. By using @bind="UserName", Blazor listens for changes in the input field and automatically updates the C# property, while simultaneously reflecting any changes made to that property back into the input field.

Event Handling

Event handling allows your components to respond to user interactions like button clicks or key presses. Instead of manually parsing DOM events, you assign a C# method directly to an event attribute:

<input @bind="UserEmail" placeholder="Enter email" />
<button @onclick="SubmitForm">Submit</button>

@code {
    private string UserEmail;

    private void SubmitForm()
    {
        // Business logic triggered by the button click
        Console.WriteLine($"Processing: {UserEmail}");
    }
}

When the user clicks the button, the SubmitForm method executes. Because of the two-way binding on the input, the UserEmail variable is guaranteed to hold the current value typed by the user at the exact moment the button is clicked.

Why This Matters

By coupling @bind with event handlers like @onclick, @oninput, or @onchange, you shift your focus from manual DOM manipulation (like document.getElementById) to state management. You simply update your C# properties, and Blazor’s rendering pipeline ensures the UI remains consistent with your application's current state. This declarative approach significantly reduces boilerplate code and prevents the common "source of truth" bugs found in traditional JavaScript-heavy frontend development.

Key Takeaway: Use @bind for seamless synchronization between your properties and UI inputs, and pair it with event directives like @onclick to trigger C# logic based on user interaction.