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.
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 "/" <PageTitle>Index</PageTitle> <h2>One-way Binding Example</h2> <p> <input type="text" @bind="FirstName" /> </p> <p> <span>Hello, @FirstName !</span> </p> @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:
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