liveBook · Manning

Onchange attribute

As explained in Pro ASP.NET Core 7, Tenth Edition

The @onchange attribute is a Blazor directive attribute that associates an element's change event with a .NET handler or expression.

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

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains handler wiring, event timing, property rerendering, and the concise @bind alternative, but not framework internals.
Examples
Uses a city input, London/Paris/Chicago values, an UpdateCity handler, and a rendered div to demonstrate synchronization.
What it assumes
Assumes basic Razor components, HTML elements, C# properties, and event handlers; demonstrates ChangeEventArgs from the example.
What you can do after
Apply it via Blazor to synchronize an editable element with a C# property and react to completed changes.
How it connects
Connects change events with ChangeEventArgs, value attributes, two-way data binding, @bind, and oninput.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.