Blazor Data Binding
Data binding is a fundamental concept in Blazor that allows you to synchronize data between your UI components and your C# code. This synchronization can be one-way (UI reflects data, or data updates UI) or two-way (UI changes update data, and data changes update UI).
One-Way Data Binding
One-way data binding allows you to display data from your component's C# code in the UI. Changes in the C# code automatically update the UI.
To achieve one-way binding, you use the @variableName
syntax within your Razor markup. For attribute binding, you use the @
symbol followed by the attribute name within square brackets, like [attribute-name]
.
Example: Displaying a Property
Consider a simple component that displays a message:
@page "/data-binding-example"
<h1>One-Way Binding Example</h1>
<p>@Message</p>
<button @onclick="ChangeMessage">Change Message</button>
@code {
public string Message { get; set; } = "Hello from Blazor!";
private void ChangeMessage()
{
Message = "Message updated!";
}
}
Live Example
@Message
Attribute Binding
You can bind values to HTML attributes as well.
<input type="text" value="@InputValue" />
<img src="@ImageUrl" alt="Dynamic Image" />
@code {
public string InputValue { get; set; } = "Initial Text";
public string ImageUrl { get; set; } = "https://via.placeholder.com/150";
}
Two-Way Data Binding
Two-way data binding is incredibly useful for forms and user input. It establishes a bidirectional link between a UI element (like an input field) and a component property. When the user types in the input field, the component's property is updated, and if the property is changed programmatically, the input field's value is also updated.
Blazor simplifies two-way binding using the @bind
directive.
Example: Two-Way Binding with an Input Field
The following example demonstrates how typing into the text box automatically updates the UserName
property.
@page "/two-way-binding"
<h1>Two-Way Binding Example</h1>
<div class="example-box">
<h4>User Profile</h4>
<label for="username">Username:</label>
<input type="text" id="username" @bind="UserName" />
<p>Current Username: @UserName</p>
<label for="age">Age:</label>
<input type="number" id="age" @bind="UserAge" />
<p>Current Age: @UserAge</p>
<button @onclick="SubmitProfile">Submit Profile</button>
</div>
@code {
public string UserName { get; set; } = "Jane Doe";
public int UserAge { get; set; } = 30;
private void SubmitProfile()
{
// In a real application, you would send UserName and UserAge to a service
Console.WriteLine($"Submitting profile for {UserName}, age {UserAge}");
// Optionally, you could clear the form or navigate
}
}
Live Example
Current Username: @UserNameLive
Current Age: @UserAgeLive
Two-Way Binding with Other Input Types
@bind
works with various input types, including checkboxes, radio buttons, and select elements, often with additional formatters or binding conventions.
<!-- Checkbox -->
<input type="checkbox" @bind="IsActive" />
<p>Is Active: @IsActive</p>
<!-- Radio Buttons -->
<input type="radio" name="color" value="Red" @bind="SelectedColor" /> Red
<input type="radio" name="color" value="Blue" @bind="SelectedColor" /> Blue
<p>Selected Color: @SelectedColor</p>
<!-- Select/Dropdown -->
<select @bind="SelectedItem">
<option value="Option1">Option 1</option>
<option value="Option2">Option 2</option>
</select>
<p>Selected Item: @SelectedItem</p>
@code {
public bool IsActive { get; set; } = true;
public string SelectedColor { get; set; } = "Red";
public string SelectedItem { get; set; } = "Option1";
}
Data Binding Conventions
Blazor has built-in support for various data types and offers implicit conversions. For example, binding a string
to a DateTime
input might automatically handle formatting.
Event Handling with Data Binding
You can combine data binding with event handlers. For instance, using @bind-value:event="oninput"
to update the data model as the user types, rather than waiting for the blur event.
<input type="text" @bind="InstantUpdateValue" @bind:event="oninput" />
<p>Instant Update: @InstantUpdateValue</p>
@code {
public string InstantUpdateValue { get; set; } = "Type here...";
}
Customizing Data Binding
For more complex scenarios, you can use @bind-value
in conjunction with @bind-value:format
to specify custom formatting or parsing for data binding.
<!-- Binding a decimal and formatting it -->
<input type="number" @bind="ProductPrice" @bind:format="F2" />
<p>Price: @ProductPrice.ToString("C")</p>
@code {
public decimal ProductPrice { get; set; } = 19.99m;
}
Understanding and effectively utilizing data binding in Blazor is key to building interactive and dynamic web applications efficiently.