The @onchange attribute connects an HTML element’s change event to a .NET handler or expression in a Blazor component. Pairing it with value="@City" creates a two-way relationship: user edits update City, while City changes update the displayed input value. section 33.4.2
Listing 33.16 The contents of the Bindings.razor file in the Blazor folder
<div class="form-group">
<label>City:</label>
<input class="form-control" value="@City" @onchange="UpdateCity" />
</div>
<div class="p-2 mb-2">City Value: @City</div>
<button class="btn btn-primary" @onclick="@(() => City = "Paris")">
Paris
</button>
<button class="btn btn-primary" @onclick="@(() => City = "Chicago")">
Chicago
</button>
@code {
public string? City { get; set; } = "London";
public void UpdateCity(ChangeEventArgs e) {
City = e.Value as string;
}
}
Use the complete Bindings.razor example to see the handler, ChangeEventArgs.Value conversion, rendered property value, and buttons that change the same property. section 33.4.2
Keep these behavior details in mind:
- Handle the event with a method such as UpdateCity(ChangeEventArgs e), or use an expression that assigns the incoming value. section 33.4.2
- Expect an input’s change event after editing finishes and focus leaves the element; use @bind-value:event="oninput" when updates should occur while typing. section 33.4.2
- Prefer @bind="City" when the value and change event form a standard two-way binding and no custom handler is needed. section 33.4.2
