In a Blazor component, @bind creates a two-way relationship between an element’s value and a property. Put @bind="City" on an input: editing the input updates City, while changing City in component code updates the input. It replaces the separate value attribute and change-event handler needed to wire up the same behavior manually. section 33.4.2
Bind a city input
In Bindings.razor, use <input @bind="City" /> alongside a display such as <div>City Value: @City</div>. Initialize City to "London" in @code, then add a button whose @onclick handler assigns "Paris". Typing changes the displayed value after the input loses focus; clicking the button changes both the display and the input. section 33.4.2
By default, binding uses the change event, so typing alone does not immediately update the property: press Tab or click elsewhere. For updates after each keystroke, replace @bind="City" with @bind-value="City" and @bind-value:event="oninput". The event must be represented by ChangeEventArgs; the supported choices described here are onchange and oninput. section 33.4.2
Listing 33.19 Specifying an event in the Bindings.razor file in the Blazor folder
<div class="form-group">
<label>City:</label>
<input class="form-control" @bind-value="City"
@bind-value:event="oninput" />
</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";
}
The complete Bindings.razor listing shows the event-specific attributes in context with the property display and buttons. section 33.4.2
For a DateTime property, @bind:culture selects a CultureInfo value and @bind:format supplies a formatting string. A date input can also use @bind="Time". These options affect how the bound date is presented; they are not needed for the basic city input. section 33.4.2
Do not confuse Blazor’s @bind directive attribute with MVC’s [Bind] attribute. [Bind] configures server-side model binding for an action parameter, including property selection and a form-data prefix; it does not establish an interactive element-to-property binding. section 28.4.2 section 28.4.3
