Learn Blazor Β· 4/15

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

csharp
@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

csharp
<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:

csharp
@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.

  1. Code updates the UI.
  2. 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.

  1. You type (UI updates Data).
  2. Your friend sees the update (Data updates UI).
    Both represent the same "truth" simultaneously.

πŸ’» Code Example

csharp
<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:

  1. value="@Property" (One-way binding)
  2. @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".

csharp
<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

  1. 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.
  2. 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

  1. Event Arguments: Blazor provides specific classes like MouseEventArgs, KeyboardEventArgs, etc.
  2. Event Prevention: Use the @on{event}:preventDefault directive.

πŸ’» Code Example: Mouse Coordinates

csharp
<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

csharp
<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?).

csharp
<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

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:

  1. It must accept a single argument: an array of user objects.
  2. Filter this array to include only users who are 30 years of age or older.
  3. From the filtered list of users, create a new array of strings. Each string must be formatted as follows: "FullName: [FirstName] [LastName], Email: [email]".
  4. Also from the filtered list, calculate the total combined yearsOfExperience.
  5. 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 userProfiles should be an array of strings.
  • The value for totalExperience should be a number.

When your function is called with the provided sampleUsers data, it should return an object with the following structure and values:

json
{
  "userProfiles": [
    "FullName: John Doe, Email: [email protected]",
    "FullName: Peter Jones, Email: [email protected]",
    "FullName: David Williams, Email: [email protected]"
  ],
  "totalExperience": 35
}
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.