Categories
ASP.NET Core

Data Binding in Blazor

Data binding is one of the most important processes in an application. Data binding is achieved through the @bind attribute in the Blazor component.

@bind attribute

The following code is an example of data binding to a textbox. This is a Blazor component code, so it contains the HTML tag and @code block in a file. Here the TextValue property value is assigned to the @bind attribute. The property value TextValue will update when the textbox loses focus. To display the updated value, the TextValue  will be displayed within the strong tag.

@page “/”

<h4>Data Binding</h4>

<input @bind=”TextValue” />

<br />
<div>
    <span>The Textbox value is: </span> <strong>@TextValue</strong>
</div>

@code {
    private string TextValue { get; set; }
}

The following is the output of the above code. Here you can see how the values are updated when the textbox loses its focus.

Data Binding in Blazor example 1

@bind:event attribute

The code below is the same as the code above. But it has @bind:event in input element. In the previous example, the textbox element updates the property variable when it loses focus. But in this example it is updated at the time of typing text using the @bind:event.

@page “/”

<h4>Data Binding</h4>

<input @bind=”TextValue” @bind:event=”oninput” />

<br />
<br />
<div>
    <span>The Textbox value is: </span> <strong>@TextValue</strong>
</div>

@code {
    private string TextValue { get; set; }
}

The following is the output of the above code. Here you can see how the values are updated when typing the text in the textbox.

Data Binding in Blazor example 2

@bind-{ATTRIBUTE} and @bind-{ATTRIBUTE}:event attributes

@bind-{ATTRIBUTE} and @bind-{ATTRIBUTE}:event helps bind the attributes. In the code below @bind-style and @bind-style:event attributes are added to the div tag. So when you set the style attribute in the textbox it will change into the div element.

@page “/”

<h4>Attribute Binding</h4>

<input type=”text” @bind=”StyleValue” />

<br />
<br />

<div @bind-style=”StyleValue” @bind-style:event=”onchange”>
    Demo Attribute Binding!
</div>

@code {
    private string StyleValue = “color:red”;
}

The following is the output of the above code. Here you can see how the div content color changes when changing the color name in the textbox.

Data Binding in Blazor exmple 3

This article explains how the @bind attribute binds value in the blazer.

If you have any questions please comment below.