Blazor Two-Way Binding Example

Using the @bind attribute Blazor allows you to bind the value of fields and properties to the HTML attributes. In this article, I will demonstrate a few examples of how to bind C# code with HTML attributes.

TextBox Two-Way Bind Example using the @bind directive

The following example binds the <input> textbox value to the C# FristName field. And FirstName displays in the span with the ‘Hello’ prefix.

blazor binding textbox example
After you enter your name and change the focus, the value of the textbox will be passed to the FirstName field and, accordingly, the value in the span element will be updated too.

@page "/"
<h2>One-way Binding Example</h2>
    <input type="text" @bind="FirstName" />
   <span>Hello, @FirstName !</span>
@code {
    private string? FirstName { get; set; } = "Type Your Name";


Improve binding using the @bind:event

Using the @bind:event=”{EVENT}” the bind will be triggered on the event. Let’s improve our binding by adding @bind:event=”oninput” and see how it works with our example:

blazor oninput binding textbox example
Now you can see that every time the text field changes, the value is immediately transferred to the FirstName variable and displayed in the span tag with the prefix Hello.


<input type="text" @bind="FirstName" @bind:event="oninput" />


You may be interested to read my article Blazor Server Vs Blazor WebAssembly

Leave a Comment