Learning Blazor Components and Data Binding with Examples

Mastering Blazor Components and Data Binding: A Beginner's Guide


Blazor, a framework for building interactive web UIs with C#, has been gaining popularity for its ability to use .NET in browser-based apps. This post aims to introduce beginners to the core concepts of Blazor, particularly focusing on “blazor components” and “blazor data binding”. These concepts are pivotal for anyone looking to dive into web development with Blazor. Whether you’re a seasoned C# developer or just starting, this post will guide you through the basics in a technical yet accessible manner.

Building Your First Blazor Component

Understanding Blazor Components

Blazor components are the building blocks of your Blazor application. They are similar to pages in traditional web applications, but with more power and flexibility. Each component is a .NET class that can have its own markup, logic, and styling. Components are reusable and can be nested within other components, allowing for a modular and maintainable structure in your applications.

Step-by-Step Guide to Creating a Basic Blazor Component

  1. Setting Up Your Environment: To start, ensure you have the .NET SDK installed and a suitable code editor, like Visual Studio or Visual Studio Code, ready.
  2. Creating a New Blazor Project: Open your terminal or command prompt and create a new Blazor project using the command: dotnet new blazorserver -o BlazorApp. This command creates a new Blazor Server App.
  3. Understanding the Project Structure: Navigate to the newly created BlazorApp directory. You will see various folders and files. The most important for now is the Pages and Shared folders, where most of your components will reside.
  4. Creating a New Component: In the Pages folder, create a new file named HelloBlazor.razor. This will be your first Blazor component.
  5. Writing Your First Component: Open HelloBlazor.razor and start by typing some Razor markup. Razor is a syntax for combining HTML with C#.
<h1>Hello, Blazor World!</h1>
<p>Welcome to your first Blazor component.</p>
  1. Running Your Application: To see your component in action, run your application with dotnet run from the command line. By default, your component won’t be displayed as the main page. You need to navigate to /HelloBlazor on your browser to see your component.

Example: Hello Blazor World Component

Code Snippet: Basic Blazor Component in C#

@page "/helloblazor"

<h1>Hello, Blazor World!</h1>
<p>Welcome to your first Blazor component.</p>

This code snippet creates a Blazor component that can be accessed directly via the /helloblazor URL. The @page directive at the top is a routing directive that makes this component accessible at a specific URL.

Data Binding and Event Handling

Concept of Data Binding in Blazor

Data binding is a feature that allows you to connect the properties of your components to your HTML elements, creating a dynamic and interactive user interface. In Blazor, data binding is seamless, allowing you to write less code while maintaining synchronization between your UI and the application’s state.

Types of Data Binding with Examples

1. One-way Data Binding

In one-way data binding, you can display a property from your C# code in your HTML, but changes in the UI will not reflect back in the code.

Example: Displaying a Message Let’s say you want to display a welcome message that is defined in your C# code.

Code Snippet:

@page "/oneway-binding"


@code {
    private string welcomeMessage = "Welcome to Blazor!";

In this example, welcomeMessage is a string property in the C# code block. The <h3> tag in the HTML section displays the value of welcomeMessage. Any change in welcomeMessage will update the UI, but changes in the UI do not affect the welcomeMessage value.

2. Two-way Data Binding

Two-way data binding creates a synchronization between the UI element and the component’s property.

Example: User Input Form Let’s create a form where the user’s input is bound to a C# property.

Code Snippet:

@page "/twoway-binding"

<label for="nameInput">Name:</label>
<input @bind="userName" id="nameInput" />

<p>You entered: @userName</p>

@code {
    private string userName = "";

In this code, the @bind directive binds the input field with the userName property. As the user types in the input field, the userName property is updated, and vice versa.

3. Event Binding

Event binding allows you to react to user actions like clicks, text input, etc., by binding these events to C# methods.

Example: Handling a Button Click Here, we’ll add functionality to handle a button click event.

Code Snippet:

@page "/event-binding"

<button @onclick="ShowMessage">Click Me!</button>
@if (showMessage)
    <p>You clicked the button!</p>

@code {
    private bool showMessage = false;

    private void ShowMessage()
        showMessage = true;

In this example, clicking the button triggers the ShowMessage method, which sets showMessage to true, displaying a message.

Example: Data Binding in a Form

Suppose you want to create a simple form that takes user input and displays it. Here’s how you can do it with two-way data binding in Blazor.

Code Snippet: Implementing Data Binding in C#

@page "/form"

<h3>Simple Form</h3>
<label for="username">Username:</label>
<input @bind="username" id="username" />

<p>You entered: @username</p>

@code {
    private string username = "";

In this example, the @bind directive creates a two-way data binding between the input element and the username property in the C# code block. As the user types in the input field, the username property is updated, and vice versa.

Handling Events in Blazor

Event handling in Blazor is straightforward. You can bind C# methods to events on HTML elements, like onclick or oninput, to perform actions when those events occur.

Example: Button Click Event

Let’s add a button to our form that clears the input when clicked.

Code Snippet: Event Handling Code

<button @onclick="ClearInput">Clear</button>

@code {
    private void ClearInput()
        username = "";

This code adds a button to the UI. The @onclick directive binds the button click event to the ClearInput method in the C# code block. When clicked, the ClearInput method sets the username property to an empty string, clearing the input field.

Parent-Child Component Communication

In Blazor, components often need to communicate with each other, especially in complex applications. This communication is primarily between parent and child components. We’ll explore how to pass data from parent to child components and vice versa, including practical examples and code snippets.

Passing Data from Parent to Child Component

To pass data from a parent component to a child component, you use component parameters. These parameters are defined in the child component and set by the parent component.

Example: Parent-Child Data Passing

Suppose you have a parent component that holds a message and a child component designed to display that message.

Child Component (MessageDisplay.razor):

@code {
    public string Message { get; set; }


Here, the MessageDisplay component has a Parameter attribute that makes Message a component parameter.

Parent Component:

<MessageDisplay Message="@parentMessage" />

@code {
    private string parentMessage = "Hello from Parent!";

In the parent component, you use the MessageDisplay component and pass the parentMessage as the Message parameter.

Receiving Data from Child to Parent Component

For the child to parent communication, the child component uses event callbacks to send data back to the parent.

Example: Child-to-Parent Communication

Let’s create an example where a child component sends a message to the parent component when a button is clicked.

Child Component (ChildComponent.razor):

<button @onclick="SendMessageToParent">Send Message</button>

@code {
    public EventCallback<string> OnMessageSend { get; set; }

    private async Task SendMessageToParent()
        await OnMessageSend.InvokeAsync("Message from Child");

In this child component, OnMessageSend is an EventCallback parameter. When the button is clicked, SendMessageToParent method is called, which triggers the OnMessageSend event callback.

Parent Component:

<ChildComponent OnMessageSend="ReceiveMessage" />


@code {
    private string messageFromChild;

    private void ReceiveMessage(string message)
        messageFromChild = message;

In the parent component, the ReceiveMessage method is bound to the OnMessageSend callback of the ChildComponent. When the child sends the message, ReceiveMessage gets called, updating messageFromChild.


In this comprehensive guide, we’ve journeyed through the basics of Blazor, focusing on components and data binding. Starting with building your first Blazor component, we explored how Blazor empowers you to create interactive web UIs using C#. We delved into the nuances of data binding, covering one-way, two-way, and event binding with practical examples. Finally, we tackled the crucial concept of parent-child component communication, demonstrating how components can interact in a Blazor application.

Blazor is a powerful and versatile framework, and these concepts form the bedrock upon which complex applications can be built. As you continue your journey with Blazor, remember that experimentation and practice are key. Dive into creating more components, play around with different types of data binding, and explore various ways components can communicate with each other. The possibilities are endless.

Whether you’re a seasoned developer or just starting, Blazor offers an exciting opportunity to build robust web applications with .NET. Keep exploring, keep learning, and most importantly, enjoy the process of building with Blazor.

One thought on “Learning Blazor Components and Data Binding with Examples

  1. Great article! Your step-by-step guide on creating Blazor components was super helpful. Made my first component in minutes!

Leave a Reply

Your email address will not be published. Required fields are marked *