Two-way data binding
22 Oct 20252 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 enable two-way binding on Syncfusion® components, use @bind-Value. In the following example, the SfTextBox component is bound to the C# textValue property. When the textbox loses focus, the bound field 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";
}
}
The following Syncfusion® Blazor components support two-way binding:
- AutoComplete
- Calendar
- ComboBox
- DatePicker
- DateRange Picker
- DateTime Picker
- DropDown List
- InPlace Editor
- Input Mask
- MultiSelect Dropdown
- Numeric TextBox
- RichTextEditor
- Splitter
- TextBox
- TimePicker
Bind a component generated dynamically using RenderFragment
Blazor render trees can be built manually with RenderTreeBuilder, which provides methods for creating and configuring components in C# code. The following example shows how to bind a value for a DatePicker component generated via RenderFragment. See steps 3 and 4 where the value binding and callback are handled.
@using Syncfusion.Blazor.Calendars
@using Syncfusion.Blazor.Buttons
<div id="component-container">
@dynamicComponent
</div>
<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));
builder.CloseComponent();
};
private void RenderComponent()
{
dynamicComponent = CreateComponent();
}
private void onChange()
{
DateValue = new DateTime(DateTime.Now.Year,DateTime.Now.Month,07);
}
}
For more information, see the Blazor documentation on manually building a render tree.