Blazor Data Binding

Tip: Data binding is a core concept in Blazor, enabling seamless synchronization between your UI and your C# code.

Understanding Data Binding in Blazor

Data binding in Blazor is the mechanism by which UI elements and C# code variables can be linked together. When a value changes in the UI, the corresponding code variable can be updated automatically, and vice versa. This significantly reduces the amount of boilerplate code you need to write for UI updates and state management.

Types of Data Binding

Blazor supports several types of data binding, each serving a specific purpose:

One-Way Binding

One-way binding updates the UI when the code variable changes, but changes in the UI do not affect the code variable.

Syntax:

<p>Message: @MyMessage</p>

In this example, if the MyMessage property in your C# code changes, the displayed text will update. However, if a user were to type into this paragraph (which isn't directly possible for <p>, but illustrative), the MyMessage variable would not change.

One-Way to Event Binding

This is a common pattern where UI events trigger updates in the code. The most frequent use case is binding input element values.

Syntax:

<input type="text" value="@MyInputValue" @onchange="HandleInputChange" />

Or, more commonly, using the shorthand:

<input type="text" @bind="MyInputValue" />

The @bind directive simplifies this by combining value binding and event handling for common input types.

Two-Way Binding

Two-way binding synchronizes data in both directions. Changes in the UI update the code variable, and changes in the code variable update the UI. The @bind directive is primarily used for this.

<input type="text" @bind="MyDataModel.Name" />
<p>Name entered: @MyDataModel.Name</p>

When the user types into the input field, the Name property of MyDataModel is updated. Conversely, if MyDataModel.Name is changed programmatically, the input field will reflect that change.

Interactive Example

Two-Way Binding Demonstration

Enter your name:

Hello, @userName!

Current count: @counter

This example demonstrates two-way binding for the userName variable. Typing in the input field updates the greeting in real-time. The Increment button also shows how event handling works in conjunction with state updates.

// In your Blazor component (.razor file)
@code {
    private string userName = "World";
    private int counter = 0;

    private void IncrementCounter()
    {
        counter++;
    }
}

Binding Complex Data

You can bind to properties of complex objects as well:

<input type="text" @bind="userProfile.Email" />
<p>Email: @userProfile.Email</p>

@code {
    public class UserProfile {
        public string Email { get; set; }
    }

    private UserProfile userProfile = new UserProfile { Email = "example@domain.com" };
}

Event Callbacks

For more complex event handling or when passing callbacks to child components, you can use EventCallback.

<!-- In parent component -->
<MyChildComponent OnMyCustomEvent="HandleCustomEvent" />

@code {
    private void HandleCustomEvent(string message)
    {
        Console.WriteLine($"Received: {message}");
    }
}

<!-- In child component (MyChildComponent.razor) -->
<button @onclick="TriggerEvent">Trigger Custom Event</button>

@code {
    [Parameter]
    public EventCallback<string> OnMyCustomEvent { get; set; }

    private void TriggerEvent()
    {
        OnMyCustomEvent.InvokeAsync("This is a custom message!");
    }
}

Data Binding Expressions

Blazor supports various data binding expressions within HTML markup:

Performance Considerations

While data binding is powerful, be mindful of performance with very large or rapidly changing data sets. Blazor's rendering model is generally efficient, but complex binding scenarios might require careful optimization. Use the Blazor Performance Profiler to identify any bottlenecks.