Data Binding & Event Handling
7 min read
Data Binding & Event Handling
π Welcome Back, Developer!
If you are reading this, you've likely set up your Blazor environment and created your first component. But let's be honest: a component that just sits there looking pretty is like a Ferrari without an engineβnice to look at, but itβs not taking you anywhere.
Today, we are going to breathe life into your application. We are moving from "Static HTML" to "Dynamic Applications."
In the industry, Data Binding and Event Handling are the bread and butter of frontend development. Without them, you don't have an app; you have a digital brochure.
1. One-Way Data Binding: Displaying C# State in the UI
π§ What is it?
One-Way Data Binding is a technique where data flows in a single direction: from your C# code (the source) to your HTML UI (the target).
π The Problem
Imagine you are building a dashboard for a bank. You want to show the user's balance. In standard HTML, you would have to write:<div>Balance: $500</div>
If the user spends money, that HTML is now a lie. You would need to write JavaScript to find that div and update its innerHTML. That is tedious, error-prone, and very 2010.
π‘ The Solution
Blazor allows you to inject C# values directly into the HTML using Razor syntax. When the C# variable changes, Blazor automatically re-renders that specific part of the DOM.
π Real Life Scenario
Think of an Airport Arrival Screen. The screen displays flight times coming from the control tower (the database/code). You (the passenger) can look at the screen, but you cannot write on the screen to change the flight time. The data flows one way: Tower β Screen.
π» Code Example
@page "/balance"
<h3>Welcome, @UserName!</h3>
<div class="card">
<div class="card-body">
<p>Current Balance: <strong>$@AccountBalance</strong></p>
<!-- You can even do logic inline! -->
<p>Status: @(AccountBalance > 0 ? "Rich π€" : "Broke πΈ")</p>
</div>
</div>
@code {
// This is our State
private string UserName = "Elon";
private decimal AccountBalance = 420.50m;
}π§ Under the Hood
When you use the @ symbol, the Razor compiler transforms your .razor file into a C# class. That HTML becomes a render tree. When AccountBalance is read, it inserts the value as a text node.
2. Event Handling: Responding to User Actions (@onclick)
π§ What is it?
Event Handling is the mechanism where C# methods are executed in response to user interactions (clicks, key presses, mouse movements) in the browser.
π The Problem
We have a balance on the screen (from the previous step), but we can't do anything with it. A button that doesn't click is just a rectangle. We need to trigger logic when the user interacts with the UI.
π‘ The Solution
Blazor uses the @on{event} syntax. The most common one is @onclick. You assign a C# method to this attribute, and Blazor acts as the glue between the browser's DOM event and your C# code.
π» Code Example
<h3>Counter App</h3>
<p>Current count: @currentCount</p>
<!--
The magic happens here.
@onclick binds the button's click event to the IncrementCount method
-->
<button class="btn btn-primary" @onclick="IncrementCount">
Click me
</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
// Blazor automatically calls StateHasChanged() after this method
// to check if the UI needs updating.
}
}π€ Funny Fact
In the old days of JavaScript, we had to do document.getElementById('btn').addEventListener(...). If you forgot to remove that listener, your browser would slowly eat all your RAM (memory leak). Blazor handles the cleanup for you. Your RAM is safe.
β‘ Industry Standard: Passing Parameters (Lambda Expressions)
A very common scenario: You have a list of items (e.g., a shopping cart), and you want to "Delete" a specific item. You need to pass the ID of that item to your function.
You cannot do: @onclick="DeleteItem(item.Id)" (This executes immediately when the page loads!).
You must use a Lambda expression:
@foreach (var item in items)
{
<p>
@item.Name
<button @onclick="() => DeleteItem(item.Id)">Delete ποΈ</button>
</p>
}
@code {
private void DeleteItem(int id)
{
// Logic to remove item with 'id'
}
}3. Two-Way Data Binding: Keeping UI and State in Sync (@bind)
π§ What is it?
Two-Way Data Binding creates a synchronization loop.
- Code updates the UI.
- User updates the UI (via an input) β Updates the Code.
π The Problem
Forms. Forms are painful.
If you use one-way binding on an <input value="@userInput">, the user can type in the box, but your C# variable userInput won't change. The connection is only Tower β Screen. We need the Screen to talk back to the Tower.
To fix this manually, you would have to listen to @onchange and manually update the variable. That's a lot of boilerplate code.
π‘ The Solution
Enter the @bind directive. It handles the input and the output automatically.
π Real Life Scenario
Think of a Google Doc shared between you and a friend.
- You type (UI updates Data).
- Your friend sees the update (Data updates UI).
Both represent the same "truth" simultaneously.
π» Code Example
<h3>Profile Editor</h3>
<div class="form-group">
<label>Enter your bio:</label>
<!--
As you type and click away (lose focus),
the 'bio' variable updates automatically.
-->
<input @bind="bio" class="form-control" />
</div>
<p><strong>Preview:</strong> @bio</p>
@code {
private string bio = "I love coding in Blazor!";
}π΅οΈ Under the Hood (Important for debugging)
@bind="Property" is actually "Syntactic Sugar" (a shortcut). The compiler converts it into two things:
value="@Property"(One-way binding)@onchange="@((ChangeEventArgs e) => Property = e.Value.ToString())"(Event handling)
Pro Tip: By default, @bind updates when the focus leaves the input box (on blur). If you want it to update while you type (like a search bar), use @bind:event="oninput".
<input @bind="searchText" @bind:event="oninput" placeholder="Search live..." />
<p>Searching for: @searchText</p>4. Event Arguments and Preventing Default Browser Actions
π§ What is it?
Sometimes a simple "Click" isn't enough. You need to know where they clicked, or which key they pressed. Also, sometimes you want to stop the browser from doing what it usually does (like reloading the page when a form submits).
π The Problem
- Args: You are building a drawing app. You need the X and Y coordinates of the mouse. A simple
void Click()doesn't give you that. - Prevention: You have a
<form>. Inside, there is a<button>Save</button>. When you click it, the browser (being helpful) tries to submit the form to a server and refreshes the whole page. In a Single Page App (SPA) like Blazor, we hate page refreshes.
π‘ The Solution
- Event Arguments: Blazor provides specific classes like
MouseEventArgs,KeyboardEventArgs, etc. - Event Prevention: Use the
@on{event}:preventDefaultdirective.
π» Code Example: Mouse Coordinates
<div style="background-color: lightgray; height: 200px;"
@onmousemove="ShowCoordinates">
Move mouse here!
</div>
<p>Mouse Position: @coordinates</p>
@code {
private string coordinates = "0, 0";
// Just accept the argument in the method signature
private void ShowCoordinates(MouseEventArgs e)
{
coordinates = $"{e.ClientX}, {e.ClientY}";
}
}π» Code Example: Stopping Form Refresh
<form @onsubmit="HandleSubmit">
<input type="text" />
<!--
Standard submit button.
Usually reloads the page.
Blazor's HandleSubmit will run, but we want to ensure
we don't lose our state to a refresh.
-->
<button type="submit">Submit</button>
</form>
@code {
private void HandleSubmit()
{
// In Blazor, @onsubmit automatically prevents default page reload
// so you can handle logic via AJAX/SignalR.
Console.WriteLine("Form submitted without page reload!");
}
}Wait, what if I want to stop a specific key?
Say you want an input where the user cannot type the letter 'Z' (because we hate Z, I guess?).
<input value="@text"
@onkeydown="KeyHandler"
@onkeydown:preventDefault="shouldPrevent" />
@code {
private string text = "";
private bool shouldPrevent = false;
private void KeyHandler(KeyboardEventArgs e)
{
if (e.Key == "z" || e.Key == "Z")
{
shouldPrevent = true;
}
else
{
shouldPrevent = false;
}
}
}π Summary Checklist
| Concept | Syntax | Use Case |
|---|---|---|
| One-Way Binding | @Variable |
Displaying text, changing classes/IDs. |
| Event Handling | @onclick="Method" |
Buttons, simple interactions. |
| Two-Way Binding | @bind="Variable" |
Input forms, checkboxes, dropdowns. |
| Live Binding | @bind:event="oninput" |
Live search bars, instant character counters. |
| Event Args | (MouseEventArgs e) |
Getting mouse pos, key pressed, screen location. |
π References & Further Reading
- Official Docs: ASP.NET Core Blazor Data Binding
- Official Docs: ASP.NET Core Blazor Event Handling
- Deep Dive: Lambda Expressions in C# (for passing args)
Challenge: Try creating a "Todo List". Use Two-Way binding for the text input, Event Handling to add it to a list, and One-Way binding to display the list using a @foreach loop!
Happy Coding! π
Challenge
You are given an array of user objects. Each object contains details about a user, including a nested name object. Your task is to implement the processUserData function to perform a series of data transformations.
The function must perform the following actions:
- It must accept a single argument: an array of user objects.
- Filter this array to include only users who are 30 years of age or older.
- From the filtered list of users, create a new array of strings. Each string must be formatted as follows:
"FullName: [FirstName] [LastName], Email: [email]". - Also from the filtered list, calculate the total combined
yearsOfExperience. - The function must return a single object with two properties:
userProfiles: The array of formatted user strings.totalExperience: The calculated total years of experience (a number).
Expected result
Your processUserData function should return a single object containing the transformed data. The object must have exactly two keys: userProfiles and totalExperience.
- The value for
userProfilesshould be an array of strings. - The value for
totalExperienceshould be a number.
When your function is called with the provided sampleUsers data, it should return an object with the following structure and values:
{
"userProfiles": [
"FullName: John Doe, Email: [email protected]",
"FullName: Peter Jones, Email: [email protected]",
"FullName: David Williams, Email: [email protected]"
],
"totalExperience": 35
}