In two-way binding, data moves from the component to the UI and from the UI to the component class. Use the @bind attribute in the property to bind two ways in Blazor. By default, the bind attribute binds the data in the OnChange event. The OnChange event triggers when the element loses focus.
Follow these steps to achieve the two-way binding in Blazor.
<div><input @bind="BindValue" @bind:event="oninput" /></div><div>
Binding Value : @BindValue</div>@code {
public string BindValue { get; set; } = string.Empty;
}
To achieve two-way binding with the Select component in Blazor, you can use the @bind directive. Here’s an example of how you can implement two-way binding with the Select component:
The input element value is updated by the @bind event in Blazor. To get the current input value, use the oninput native event of the input element and get the current input value.
You can refresh the Blazor component using the SignalR concept without reloading the page. When using SignalR, saving the changes in one page notifies the changes made to other clients. During the notification process, call the data loading method to reload the changes made to that component without reloading the entire page.
@code{
public List<Order> Orders { get; set; }
private HubConnection hubConnection;
protectedoverridevoidOnInitialized()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/chathub"))
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
LoadData(); //update the data
StateHasChanged();//Refresh the component using updated data
});
await hubConnection.StartAsync();
}
protectedasyncvoidLoadData()
{
//load all the orders from the server.
}
}
You can bind a specific
format for the DateTime value by using the @bind:format attribute
of the INPUT element and assign it with the supported date format string value.
Refer to the following code sample.
<input @bind="Value" @bind:format="@Format" />
@code{
[Parameter]
public DateTime Value { get; set; } = DateTime.Now;
[Parameter]
public string Format { get; set; } = "yyyy-MM-dd";
}
To format the DateTime
and numbers to the local culture, use the @bind:format attribute of the
INPUT element that supports the date format string value .
Refer to the following code sample.
<input @bind="Value" @bind:format="@Format" />
@code{
[Parameter]
public DateTime Value { get; set; } = DateTime.Now;
[Parameter]
public string Format { get; set; } = "yyyy-MM-dd";
}
You can bind an input of type time in Blazor by using the @bind property to the time value and @bind:format property to
specify the supported time format in the DOM input element.
Refer to the following code sample.
<inputtype="time" @bind="SomeTime" @bind:format="HH:mm"/>@code {
public DateTime SomeTime = new DateTime();
}
String comparison with case insensitivity can be carried out using the String.Compare method, where the first and second parameters are the strings to be compared and the third parameter is for ignoring case sensitivity (case insensitive comparison).
You can check/uncheck the checkbox in the Blazor programmatically by using the @bind parameter in the checkbox. Assign a Boolean property to @bind in the checkbox and toggle the Boolean property programmatically.
@page<inputtype="checkbox" @bind="@boolvalue" />
<br />
Checkbox: @val
<br />
<button class="btnbtn-primary" @onclick="@ToggleCheckbox ">toggle</button>@code {
public bool boolvalue { get; set; }
public string val;
void ToggleCheckbox()
{
if (boolvalue)
{
val = "unchecked";
}
else
{
val = "checked";
}
boolvalue = !boolvalue;
}
}
To set the active value on a select dropdown control, you must bind a property to the value in the select component and change that bind property in the event call
@page "/dropdown"<selectclass="form-control"value="@listdefault" @onchange="@OnSelect" style="width:150px">@foreach (var template in templates)
{
<option value=@template>@template</option>
}
</select>
<h5>@selectedString</h5>
<select class="form-control" value="@citydefault" @onchange="@OnSelectCity" style="width:150px">@foreach (var template in citytemplates)
{
<option value=@template>@template</option>
}
</select>
<h5>@selectedCity</h5>
<button class="btnbtn-primary" @onclick="@Change">Change</button>
@code {
List<string> templates = new List<string>() { "America", "China", "India", "Russia", "England" };
List<string> citytemplates = new List<string>();
List<string> usa = new List<string>() { "Los-Angeles", "Florida", "Newyork", "Washington", "California" };
List<string> china = new List<string>() { "Wuhan", "Beijing", "Shanghai", "Macau", "Taipei " };
List<string> india = new List<string>() { "New-Delhi", "Mumbai", "Chennai", "Bangalore", "Hyderabad" };
List<string> russia = new List<string>() { "Moscow", "Saint Petersburg", "Novosibirsk", "Yekaterinburg", "Kazan" };
List<string> england = new List<string>() { "Birmingham", "Cambridge", "Manchester", "Leicester", "London" };
string selectedString = "";
string selectedCity = "";
string listdefault = "India";
string citydefault = "Mumbai";
void OnSelect(ChangeEventArgs e)
{
if (e.Value.ToString() == "America")
{
citytemplates = usa;
}
else if (e.Value.ToString() == "China")
{
citytemplates = china;
}
else if (e.Value.ToString() == "India")
{
citytemplates = india;
}
else if (e.Value.ToString() == "Russia")
{
citytemplates = russia;
}
else
{
citytemplates = england;
}
selectedString = "Selected Country is: " + e.Value.ToString();
StateHasChanged();
Console.WriteLine("It is definitely: " + selectedString);
}
void OnSelectCity(ChangeEventArgs e)
{
selectedCity = "Selected CIty is: " + e.Value.ToString();
Console.WriteLine("It is definitely: " + selectedString);
}
void Change(MouseEventArgs args)
{
listdefault = "Russia";
}
protected override void OnInitialized()
{
citytemplates = india;
citydefault = "Chennai";
base.OnInitialized();
}
}
In the above sample, the city dropdown is changed based on the country selected in the country dropdown.
To get the checkbox value when it is checked or unchecked use the onchange event by calling a method in onchange event using lambda expression and passing the checkbox value to it.
@foreach (var check inCheckBoxList())
{<inputclass="custom-checkbox"type="checkbox" @onchange="eventArgs => { CheckboxClicked(check, eventArgs.Value); }" />@check<br />}@code {
public List<string> CheckBox { get; set; } = new List<string>();
void CheckboxClicked(string CheckID, object checkedValue)
{
if ((bool)checkedValue)
{
if (!CheckBox.Contains(CheckID))
{
CheckBox.Add(CheckID);
}
}
else
{
if (CheckBox.Contains(CheckID))
{
CheckBox.Remove(CheckID);
}
}
}
public List<String> CheckBoxList()
{
List<String> checkBox = new List<String>();
checkBox.Add("CheckBox 1");
checkBox.Add("CheckBox 2");
return checkBox;
}
}
This ObservableCollection (dynamic data collection) provides notifications when items are added, removed, and moved. The implemented INotifyCollectionChanged provides notifications when dynamic changes of adding, removing, moving, and clearing the collection occur. The implementation of INotifyPropertyChanged notifies when property value has changed in client side. Here, Order class implements the interface of INotifyPropertyChanged and it raises the event when CustomerID property value was changed.
In the sample, we have add, delete and update buttons where the observable data for the table will be populated, removed or updated through the button click.
We can get child component values in the parent component by creating a reference to the child component using the @refdirective in the Parent component. Using the reference instance, you can access the child component values in the parent.
In the following example, textbox refers to the TextBoxComponent (child component) instance. Using textbox, we can access the properties and values in the Parent component.
Two-way binding is having a bidirectional data flow, i.e., passing the value from the property to the UI and then from the view (UI) to the property. Blazor provides support for two-way binding using the bind attribute.
Syntax for creating two-way binding property:
@bind-{Parameter_name}={Variable_name}
For e.g.., in InputDate,
a form component can be used to achieve two-way data binding with input date
values in a Blazor application.
In this example code, when the value of _test.DateValue is changed in the code or user changes the date in the InputDate component, the same will be reflected in the paragraph, “Selected Date”.
One-way (unidirectional) binding is all about moving data in one direction from the “Parameter/Property” to the UI (components). You just need to add the @ symbol to the variable name (for example, @yourVariable).
For example, one-way binding with an input date value can be achieved using the InputDate component (form component in Blazor) as follows in an application.
In this example, the property DateValue in _test class is bound to the InputDate component’s value property using the value attribute. A form is defined by the EditForm component.
The value of an input element is updated in the wrapper with the change events of elements in Blazor. To get the current value for each character input, you must use the oninput event of the input element. This can be achieved by binding the oninput event (native event) using the @bind:event=“oninput“.
DOM attributes are rendered based on .NET parameters. If the parameter value is true, the attribute is rendered minimized, otherwise it’s not. Refer to the code example to render the checked attribute conditionally.
By default, Blazor detects changes and reflects
them in the UI automatically. However, there might be a situation where we have
to manually trigger changes. StateHasChanged
informs the component that its state has changed, but it does not render the
component. The component will decide when to render itself.
You can’t do that in a synchronous method, so you should async your code to give the component a chance to render.
You can bind events to DOM elements started with the on<event> with a delegate-type value. The attribute’s name always starts with “on.” In the following code example, the “UpdateHeading” event is triggered when the button is clicked.
Two-way is having a bi-directional data flow, i.e., passing the value from the property to the UI and then from the view (UI) to the property as well The synchronization of data flow between model and view is achieved using the bind attribute in Blazor. Refer to the following code example for two-way data flow.
@page"/"
Enter your name: <input type="text"@bind="@Name" /><br />
<h2>Hello, @Name!</h2>
@code {
private string Name { get; set; } = "Blazor";
}
Yes, this is a known bug. While creating custom components with the native events onclick and onchange, the event that is not bound in the sample component is rendered as null.
You can refer to the following thread for more information with an example code snippet.