- If you are new to Blazor, I would firmly recommend you to go through the central article on Blazor which ought to be practically ready to address every one of your inquiries in regards to what Blazor is.
- Visual Studio or VS Code installed in your machine.
- Blazor templates
- Blazor Language Services
One-way Data binding
In simple words, one-way data binding is data flowing from component class to component view (Razor page). In this view, we bind the names which we have already defined in the component class. In Blazor, when modifying a one-way binding the application is going to be responsible for making the change. This could be in response to user action or event such as a button click. The point is, that the user will never be able to modify the value directly, hence one-way binding.
Let's take a look at some examples.
Create a Blazor Server app in Visual Studio.
Choose the target framework for this project.
Now will create a class inside the Data folder to define the property so that one-way data binding happens from component class to component view.
DataBind.cs
- using Microsoft.AspNetCore.Components;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace DataBindingBlazor.Data
- {
- public class DataBind : ComponentBase
- {
- public string Name = "Jay Krishna Reddy";
- }
- }
Index.razor
let's inherit the class in the index.razor page to invoke the properties which is residing in Databind class and will be assigned to the HTML property which is highlighted below. This is how the one-way data-bind works.
- @page "/"
- @inherits Data.DataBind
-
- <h1>Data Binding</h1>
- <hr />
- <h3>One-way Data binding</h3>
-
- <div>
- <b>Name :</b> @Name @*Data flow from class to view*@
- </div>
Output
Two-way Data binding
Now we know all about one-way data binding. The primary use case for two-way data binding in forms and can be achieved by using "@bind" attribute. Blazor has 3 different forms which allow developers to be very specific about how they want this binding to occur.
Index.razor
The bind attribute will look for the assigned value in the class component and will bind accordingly.
- <h3>Two-way Data binding</h3>
-
- <div>
- <b>Name :</b> <input @bind="Name" /> @*Two-way Data binding*@
- </div>
Output
Try adding the name in the text box and see it will appear in all the places where we used the property name
Hope this article helps you in understanding the concepts like one-way & two-way data binding.
keep learning ......!