Blazor - Two-way Data Binding

10 May 20222 minutes to read

Syncfusion Blazor components provide data binding features with the @bind-value Razor directive attribute with a field, property, or Razor expression value. By default, the bind-value attribute binds the data value in the OnChange event. The OnChange event triggers when the element loses its focus.

To perform a two-way binding Syncfusion Blazor components, use the bind-Value attribute. In the below example, SfTextBox component value to the C# textValue property. When an SfTextBox component loses focus, its bound field or property is updated.

@using Syncfusion.Blazor.Inputs

<p>Binded value in TextBox is: <b>@textValue</b></p>

<SfTextBox @bind-Value="textValue"></SfTextBox>

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

    protected override void OnInitialized()
        textValue = "Syncfusion Blazor";

Two-Way Binding in Blazor

The following Syncfusion Blazor components support two-way binding:

Bind component generated dynamically using RenderFragment

You can build Blazor render trees manually with RenderTreeBuilder which provides methods for building and manipulating components manually in C# code. The following code explains how to bind value for DatePicker component which is generated dynamically using RenderFragment. Refer sequence 3,4 where binding and call back is handled.

@using Syncfusion.Blazor.Calendars
@using Syncfusion.Blazor.Buttons

<div id="component-container">

<SfButton ID="dynamic-button" Content="Render DatePicker" @onclick="RenderComponent"></SfButton>
<SfButton ID="button" Content="Change Date" @onclick="onChange"></SfButton>

@code {
    public DateTime? DateValue { get; set; } = DateTime.Now.Date;
    private RenderFragment dynamicComponent { get; set; } 
    private RenderFragment CreateComponent() => builder =>
        builder.OpenComponent(0, typeof(SfDatePicker<DateTime>));
        builder.AddAttribute(1, "ID", "MyDynamicId");
        builder.AddAttribute(2, "Placeholder", "Choose a date");
        //Binding the value property with DateValue property.
        builder.AddAttribute(3, "Value", DateValue);
        builder.AddAttribute(4, "onchange", Microsoft.AspNetCore.Components.EventCallback.Factory.
                CreateBinder(this, _value => DateValue = _value, DateValue));

    private void RenderComponent()
        dynamicComponent = CreateComponent();
    private void onChange()
        DateValue = new DateTime(DateTime.Now.Year,DateTime.Now.Month,07);

Binding in Blazor when build a render tree

Refer Manually build a render tree topic for more details.