
Input Handling in Blazor Apps: @bind vs @oninput vs @onchange
Learn the difference between @bind, @oninput, and @onchange in Blazor. Practical examples showing when to use each directive for real-time validation, live search, and form submission.
Input Handling in Blazor Apps: @bind vs @oninput vs @onchange
Blazor provides various ways to handle input fields, making it a powerful framework for building interactive web applications. Understanding when and how to use @bind, @oninput, and @onchange can significantly enhance your Blazor apps.
@bind — Two-Way Data Binding
The @bind directive provides two-way data binding between an input field and a property.
Best for: Complex forms, real-time synchronization with your data model.
<input type="text" @bind="userName" />
<p>Your username is: @userName</p>
@oninput — Instant Feedback on Every Keystroke
@oninput triggers on every keystroke or value change.
Best for: Real-time validation, live search.
<input type="text" @oninput="HandleInput" />
<p>Current input: @currentInput</p>
@code {
private string currentInput;
private void HandleInput(ChangeEventArgs e)
{
currentInput = e.Value.ToString();
}
}
@onchange — Action on Final Value
@onchange triggers only when the input loses focus and the value has changed.
Best for: Form submission, batch updates.
<input type="text" @onchange="HandleChange" />
<p>Final input: @finalInput</p>
@code {
private string finalInput;
private void HandleChange(ChangeEventArgs e)
{
finalInput = e.Value.ToString();
}
}
Combining @bind and @oninput
For live search with data model sync:
<input type="text" @bind="searchQuery" @oninput="PerformSearch" />
@code {
private string searchQuery;
private void PerformSearch(ChangeEventArgs e)
{
searchQuery = e.Value.ToString();
// Perform search logic here
}
}
Conclusion
- Use
@bindfor real-time synchronization between UI and data model. - Use
@oninputfor immediate per-keystroke feedback. - Use
@onchangefor actions that should happen after the user finishes input.
