Appearance
Data Binding in Blazor
One-way binding
One-way data binding is used to display data in the UI. The data flows from the component to the UI elements.
razor
<div>@message</div>
<p>Count: @count</p>
<span>Total: @CalculateTotal()</span>
@code {
private string message = "Hello Blazor";
private int count = 0;
private decimal CalculateTotal() => 100.50m;
}
Two-way binding
Two-way data binding allows changes in the UI to be reflected in the code and vice versa. Blazor provides two main binding syntaxes: @bind
and @bind-Value
.
Using @bind
@bind
is used with standard HTML elements and is the default binding syntax in Blazor:
razor
<input @bind="message" />
<input @bind="message" @bind:event="oninput" />
<input @bind:get="message" @bind:set="UpdateMessage" />
@code {
private string message = "";
private void UpdateMessage(string value)
{
message = value;
// Additional processing
}
}
Using @bind-Value
@bind-Value
is specifically used with Blazor's built-in form input components and provides additional features like:
- Automatic type conversion
- Integration with form validation
- Works with EditForm component
razor
<EditForm Model="model">
<InputText @bind-Value="model.Name" />
<InputNumber @bind-Value="model.Age" />
<InputSelect @bind-Value="model.Category">
<option value="">Select...</option>
<option value="A">Category A</option>
<option value="B">Category B</option>
</InputSelect>
</EditForm>
@code {
private UserModel model = new();
}
Binding with Different Events
You can specify which event triggers the binding update:
razor
<!-- Update on input (every keystroke) -->
<input @bind="message" @bind:event="oninput" />
<!-- Update on change (default - when focus is lost) -->
<input @bind="message" @bind:event="onchange" />
Format Strings
You can specify format strings for numeric and date values:
razor
<input @bind="price" @bind:format="C2" />
<input @bind="date" @bind:format="yyyy-MM-dd" />
@code {
private decimal price = 19.99m;
private DateTime date = DateTime.Now;
}