Blazor Server UI Component Example

Introduction

In this blog, I will present Blazor Server UI Component mechanism, and I will implement a solution example to demonstrate Blazor Server UI Component functionalities with code behind.

How Blazor Server Components Works

Blazor is a user interface extension running on ASP.Net Core. At the first request (the user loads a Blazor page in his browser), the Web server will return a javascript file (blazor.server.js), which contains the Blazor client. This client will subscribe to an integrated SignalR connection executed by the web application. Blazor automatically publishes a SignalR hub.

A default SignalR connection between the browser and the server uses the WebSocket protocol (WS or WSS for encrypted communication). Websocket is a full duplex TCP protocol.

Every communication between the browser and the server goes through this SignalR hub. The Razor component paint the screen, it’s loading partially in the current page. The Razor component class will be on the call stack and this instance of the class will remain in server memory for the duration of the user's page is open in their browser.

Operation of Blazor components

Figure 1: Operation of Blazor components on user's browser loading page 

How to create Blazor UI Component with code behind

Referring to Figure 1, the Razor component is split in two:

  • the client part (.razor)
  • the server part (.razor.cs)

Like Webforms, it is possible to separate the html code repainted on the client from the C# logic on the server side. In a professional context, this separation allows to realize the client part by a Web integrator and the C# part by a .Net developer.

To create the behind code of a Razor component, you need :

  • Create a file with the same name as the razor component with the extension razor.cs
  • Create in this file a partial class with the same name as the razor component
  • Import the reference to Microsoft.AspNetCore.Components (using Microsoft.AspNetCore.Components). Be careful, the solution file _Imports.razor only works with files with extension razor and not razor.cs.

Integrate the concept of code behind component in a Blazor Server solution

In this example, I will create a component with code behind integrating a timer. The use of SignalR will be of type RPC (Remote Procedure Protocol) for a repaint from the server of each instance of the component on the client side. The component will be customizable in order to demonstrate the client-server uniqueness of each component.

1. Create a solution and add new « Component » folder. By default namespace will be : SolutionName.Component.

2. Create UI Component with name TimeZone.razor and code behind file with name TimeZone.razor.cs in Component folder (It is possible to create them in different folders).

TimeZone.razor code

<label for="appt-time">@City</label>
<input id="appt-time" type="time" name="appt-time" value=@DateTimeUpdate step="2" />

TimeZone.razor.cs code

using System.Timers;
using Microsoft.AspNetCore.Components;

//declaration of the class in the same namespace as the razor component
namespace BlogComponentUI.Component;

//Use of a partial class with the same name as the razor file
public partial class TimeZone
{
    [Parameter]
    public double TimerInterval{get;set;}

    [Parameter]
    public string? City {get;set;}

    [Parameter]
    public double TimeZoneGMTAdd {get;set;}

    public string? DateTimeUpdate{get;set;}

    //Method invoked when component his ready to start,
    //having received its initial parameters from its parent in the render tree
    protected override void OnInitialized()
    {
        System.Timers.Timer timer=new System.Timers.Timer(TimerInterval);
        timer.Elapsed+=GenerateTimeZone;
        timer.Enabled=true;
    }

    public void GenerateTimeZone(Object? source, ElapsedEventArgs? e)
     {
        DateTime dtUTC=DateTime.Now.ToUniversalTime();
        DateTimeUpdate=dtUTC.AddHours(TimeZoneGMTAdd).ToLongTimeString();
        
        //Notify client to repaint component (change component state) 
        InvokeAsync(StateHasChanged);
     }
}

3. Add UI Component to index.razor  and fill in parameters

Index.razor code

@page "/"
@using BlogComponentUI.Component


<TimeZone City="Port Louis" TimeZoneGMTAdd="+4" TimerInterval="10000" /><br /><br />
<TimeZone City="Mumbai" TimeZoneGMTAdd="+5.5" TimerInterval="5000" /><br /><br />
<TimeZone City="Paris" TimeZoneGMTAdd="+1" TimerInterval="1000" /><br /><br />
<TimeZone City="New York" TimeZoneGMTAdd="-4" TimerInterval="15000" /><br /><br />
<TimeZone City="Tokyo" TimeZoneGMTAdd="+9" TimerInterval="2000" /><br /><br />

Result

In conclusion, we notice that each instance of the component has its own timer with its own parameterized information. This C# logic code behind (server side) is in a separate code from the presentation. The asynchronous method ComponentBase.InvokeAsync, taking as parameter the method ComponentBase.StateHasChanged, notifies the client of the change of state of the component and triggers component's repainting (like RPC architecture).

The separation of the C# logic and the presentation leads to several advantages:

  • The clear separation between the Controller and the View
  • Clear separation between server-side logic and client-side repainting and interactions
  • Facilitates code maintenance and scalability
  • Allows for easier code reuse
  • More understandable management of component state
  • Facilitates unit tests on the component
  • Increase productivity by separating the tasks of the Web integrator and the C# developer

See you in my next post.