Blazor two way data binding example


In this video we will understand two way data binding in Blazor with a very simple but a real world example. As the user types in the Description textbox, we want to display the total number of characters typed so far as shown in the image below.

blazor two way data binding example

Blazor component class

Create Description property in the component class. It's important you initialise the property to an empty string, otherwise you will get a null reference exception at runtime.

public string Description { get; set; } = string.Empty;

Blazor component view

<div>
    <textarea @bind="Description" @bind:event="oninput" />
</div>
<div>
    Count : @Description.Length
</div>

Code exaplanation

  • Bind the <textarea> element to the Description property using the bind attribute.
  • With the bind attribute, we get two way data-binding i.e the <textarea> element displays the value of the Description property and if we change the text in the <textarea> element on the UI, the Description property in the component class is automatically updated.
  • By default, the bind attribute binds data on change event. Change event is triggered when the element loses focus.
  • However, we want the characters count as the user is typing in the <textarea> element. We do not want to wait until the element loses focus. 
  • This means we want to change the default event of data binding. We do this by using the event parameter of the bind attribute.
  • In this example, we changed the default binding event from onchange to oninput.
  • The input event is fired as we type in the <textarea> element and the Description property is updated with the new value.
  • To display the count of characters the UI is bound to @Description.Length




© 2020 Pragimtech. All Rights Reserved.