Blazor lets you bind HTML controls to properties so that changing values are automatically displayed in the user interface (UI).
Suppose you’re developing a page that collects information from customers about their pizza preferences. You want to load the information from a database and enable customers to make changes, such as recording their favorite toppings. When there’s a change from the user or an update in the database, you want the new values to display in the UI as quickly as possible.
In this unit, you learn how to use data binding in Blazor to tie UI elements to data values, properties, or expressions.
What is data binding?
If you want an HTML element to display a value, you can write code to alter the display. You need to write extra code to update the display when the value changes. In Blazor, you can use data binding to connect an HTML element to a field, property, or expression. This way, when the value changes, the HTML element is automatically updated. The update usually happens quickly after the change, and you don’t have to write any update code.
To bind a control, you would use the @bind directive:
razorCopy
@page "/"
<p>
Your email address is:
<input @bind="customerEmail" />
</p>
@code {
private string customerEmail = "user@contoso.com"
}
In the preceding page, whenever the customerEmail variable changes its value, the <input> value updates.
Note
Controls, such as <input>, update their display only when the component is rendered and not when a field’s value changes. Because Blazor components render after any event handler code executes, in practice, updates are typically displayed quickly.
Bind elements to specific events
The @bind directive is smart and understands the controls it uses. For example, when you bind a value to a textbox <input>, it binds the value attribute. An HTML checkbox <input> has a checked attribute instead of a value attribute. The @bind attribute automatically uses this checked attribute instead. By default, the control is bound to the DOM onchange event. For example, consider this page:
razorCopy
@page "/"
<h1>My favorite pizza is: @favPizza</h1>
<p>
Enter your favorite pizza:
<input @bind="favPizza" />
</p>
@code {
private string favPizza { get; set; } = "Margherita"
}
Leave a Reply