Published: July 30 2020

ASP.NET Core Blazor WebAssembly - Communication Between Components

Built with ASP.NET Core Blazor WebAssembly 3.2.1

Other versions available:

This is a quick tutorial to show how you can send messages between components in a Blazor WebAssembly (WASM) application. It includes an example Blazor app that sends messages from a home component to a main layout component via a message service.

The tutorial project is available on GitHub at https://github.com/cornflourblue/blazor-webassembly-communication-between-components.

The way to communicate between any two components in a blazor app is to use C# events and delegates, I won't go too much into the details about how events and delegates work here since it's a big subject, but in a nutshell they enable publishing and subscribing to events in C#.

A publisher class declares an event with the type of handler required for the event (a.k.a. the delegate).

A subscriber class subscribes to an event by adding a handler method (that matches the event delegate) to the event of the publisher class (e.g. publisher.onEvent += myEventHandler;), and unsubscribes by removing the event handler (e.g. publisher.onEvent -= myEventHandler;)

For more info on C# events and delegates see https://csharpindepth.com/articles/Events.


Declaring an event

This code is from the example message service and declares the OnMessage event that requires a handler delegate of type Action<string>, which is a handler method that accepts a single string parameter and returns void (e.g. void MessageHandler(string message) {}).

public event Action<string> OnMessage;


Subscribing and unsubscribing to an event

This code is from the example main layout component and shows how it subscribes to the MessageService.OnMessage event when the component is initialized and then unsubscribes when it is disposed.

protected override void OnInitialized()
{
    // subscribe to OnMessage event
    MessageService.OnMessage += MessageHandler;
}

public void Dispose()
{
    // unsubscribe from OnMessage event
    MessageService.OnMessage -= MessageHandler;
}


Publishing an event

This code is from the example message service and invokes the OnMessage event with the message parameter.

The C# null conditional operator (?.) is used to check if OnMessage is null before attempting to invoke it, an event is null when it has no subscribers.

OnMessage?.Invoke(message);


Blazor WebAssembly Component Communication Example

(Hosted on GitHub Pages at https://cornflourblue.github.io/blazor-webassembly-communication-between-components/)


Tools required to run the Blazor WebAssembly Example Locally

To develop and run ASP.NET Core Blazor applications locally, download and install the following:

  • .NET Core SDK - includes the .NET Core runtime and command line tools
  • Visual Studio Code - code editor that runs on Windows, Mac and Linux
  • C# extension for Visual Studio Code - adds support to VS Code for developing .NET Core applications

For detailed instructions see ASP.NET Core - Setup Development Environment.


Running the Blazor WebAssembly App Locally

  1. Download or clone the tutorial project code from https://github.com/cornflourblue/blazor-webassembly-communication-between-components
  2. Start the app by running dotnet run from the command line in the project root folder (where the BlazorApp.csproj file is located)
  3. Open a new browser tab and navigate to the URL http://localhost:5000


Blazor Message Service

With the message service you can subscribe to new messages in any component via the OnMessage event, send messages from any component with the SendMessage(string message) method, and clear messages from any component with the ClearMessages() method.

The ClearMessages() method actually just sends a null message by calling OnMessage?.Invoke(null);, the logic to clear the messages when a null message is received is in the main layout component below.

using System;

namespace BlazorApp.Services
{
    public interface IMessageService
    {
        event Action<string> OnMessage;
        void SendMessage(string message);
        void ClearMessages();
    }

    public class MessageService : IMessageService
    {
        public event Action<string> OnMessage;

        public void SendMessage(string message)
        {
            OnMessage?.Invoke(message);
        }

        public void ClearMessages()
        {
            OnMessage?.Invoke(null);
        }
    }
}


Blazor Main Layout Component that Receives Messages

The main layout component uses the message service to subscribe to new messages and add them to the messages list which is rendered below the @Body in a @foreach loop, a null message tells the component to clear the messages list. After a message is received the StateHasChanged() method is called to trigger an update to the UI.

@inherits LayoutComponentBase
@implements IDisposable
@inject IMessageService MessageService

<!-- main app container -->
<div class="container text-center my-3">
    @Body
    @foreach (var message in messages)
    {
        <div class="alert alert-sm alert-info">@message</div>
    }
</div>

@code {
    private List<string> messages = new List<string>();
    
    protected override void OnInitialized()
    {
        // subscribe to OnMessage event
        MessageService.OnMessage += MessageHandler;
    }

    public void Dispose()
    {
        // unsubscribe from OnMessage event
        MessageService.OnMessage -= MessageHandler;
    }

    private void MessageHandler(string message)
    {
        if (message != null)
            messages.Add(message);
        else
            messages.Clear();
            
        StateHasChanged();
    }
}


Blazor Home Component that Sends Messages

The home component uses the message service to send and clear messages that are displayed by the main layout component.

@page "/"
@inject IMessageService MessageService

<div class="card mb-3">
    <h4 class="card-header">Blazor WebAssembly Component Communication</h4>
    <div class="card-body">
        <button @onclick="SendMessage" class="btn btn-primary mr-2">Send Message</button>
        <button @onclick="ClearMessages" class="btn btn-secondary">Clear Messages</button>
    </div>
</div>

@code {
    private void SendMessage()
    {
        MessageService.SendMessage("Message from Home Component to Main Layout Component!");
    }

    private void ClearMessages()
    {
        MessageService.ClearMessages();
    }
}

 


Need Some Blazor Help?

Search fiverr for freelance Blazor developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by