Blazor WASM Data Binding
Blazor
31 Articles
In this article, lets learn about data binding in blazor wasm apps.
Note: If you have not done so already, I recommend you read the article on Blazor Wasm Components.
Table of Contents
- Why Data Binding in blazor components?
- One Way / Uni Directional Data Binding
- Two Way / Bi Directional Data Binding
- Summary
Why Data Binding in blazor components?
Gone are the days we used to make an ajax post from UI and bind data in our code behind or in controllers. We also have used form submit and get the data in code behind or in controllers by reading from form like formName["inputName"]. Now Data Binding in blazor components helps us to bind data to an input element using Razor directive attribute with field, property, or Razor expression value.
There are two ways of data binding,
- One Way / Uni Directional Data Binding.
- Two Way / Bi Directional Data Binding.
One Way / Uni Directional Data Binding
One way / Uni Directional data binding is used to bind data to field or property in uni directional flow. This means that user will not be able to directly modify the value. It can be done only as a result of user action or event such as button click.
This can be useful to set a label value dynamically or to set a css class value or to set a value to a hidden field.
The razor syntax for that is @bind
Code Sample - One Way Data Binding
Two Way / Bi Directional Data Binding
Two way / Bi Directional data binding is used to bind data to field or property in bi directional flow. Thus allowing values to be updated from both sides.
This will be useful to bind data to a form inputs which you can use to collect data from user. You can also use @oninput bind event to bind data instantaneously. This can be used in search input to instantaneously search data and list to user.
The razor syntax for that is,
- @bind-value=Property
- @bind-value=Property @bind-value:event="onevent"
Code Sample - Two Way Data Binding
Summary
In this article, we learn't about what is data binding (both one way and two way) in blazor components and experienced a live demo. In our next article let's learn about what is event callback and how to communicate between components.