Data Binding in Blazor

Blazor is a Single Page Application development framework. The name Blazor is a combination/mutation of the words Browser and Razor (the .NET HTML view generating engine). The implication being that instead of having to execute Razor views on the server in order to present HTML to the browser, Blazor is capable of executing these views on the client.

Blazor app with client-side execution


Blazor also supports executing SPAs on the server.


As Blazor is an SPA framework, it supports features like components, one-way & two-way data binding etc. An application built with Blazor, runs completely in the browser. Blazor supports 3 kinds of data binding

  • One-way data binding

  • Two-way data binding

  • Event binding


Pre-requisites

  1. If you are new to Blazor, I would strongly suggest you to go through the fundamental article on Blazor which should be pretty much able to answer all your questions regarding what Blazor is.

  2. Basic knowledge about Razor. You may refer official Microsoft docs for some quick idea about Razor - https://bit.ly/2PrgbnI.

  3. Visual Studio or Visual Studio code installed in your system.

  4. Blazor language services

  5. Command Line: dotnet new -i Microsoft.AspNetCore.Blazor.Templates


One-way data binding

One-way data binding in Blazor is the process of rendering the View as per the value in the Model. Sometime the Model can be just a property or a simple variable. In the previous article, we had tried creating a simple application using Blazor’s inbuilt HelloWorld template. Let’s open the counter component i.e. Counter.cshtml file and see how it has implemented one-way data binding. A Blazor component is a reusable piece of code & UI.

 @page "/counter"
 <h1>Counter</h1>
 <p>Current count: @currentCount</p>
 <button class="btn btn-primary" onclick="@IncrementCount">Click me</button>
 
 @functions {
 int currentCount = 0;
 void IncrementCount()
 {
 currentCount++;
 }
 }


Let’s remove some of the lines to make this simpler to understand.


 @page "/counter"
 <h1>Counter</h1>
 <p>Current count: @currentCount</p>
 
 @functions {
 int currentCount = 0;
 }

Now, our Counter component has a single member defined in the @functions block. In this case, it constitutes a variable and