Awesome Blazor

Nicola Sante Dipierro
7 min readNov 14, 2019

Once upon a time a group of javascript frameworks, made with typescript bones, had conquered the world of frontend development doing what they wanted by manipulating the DOM, but those times were about to end… From the father of one of these our savior was born forged by web assemblies: his name is Blazor!

Blazor is here

Steven Sanderson, one of the main author of Knockout.js, has created for us an awesome framework for building interactive client-side web UI with .NET. The power inside it, it’s the ability to create web pages written in c# instead of JavaScript or Typescript. In this way the implicit advantages are:

  • Leverage the existing .NET ecosystem of .NET libraries.
  • Share app logic across server and client.
  • Benefit from .NET’s performance, reliability, and security.
  • Stay productive with Visual Studio on Windows, Linux, and macOS.
  • Build on a common set of languages, frameworks, and tools that are stable, feature-rich, and easy to use.

And this is only the begin.

Blazor allow you to write UI components using Razor sintax, like MVC or Razor Pages using binding concepts and allowing MVVM pattern.

But unlike Razor Pages and MVC, which are built around a request/response model, blazor components are used specifically for client-side UI logic and composition.

Hosting models

The principal hosting model for Blazor is running client-side in the browser on WebAssembly. Yes, I wrote correctly and Yes, you read right.

The app is executed directly on the browser UI thread. The app’s assets are deployed as static files to a web server or service capable of serving static content to clients.

Webassembly hosting

The Blazor WebAssembly hosting model offers several benefits:

  • There’s no .NET server-side dependency. The app is fully functioning after downloaded to the client.
  • Client resources and capabilities are fully leveraged.
  • Work is offloaded from the server to the client.
  • An ASP.NET Core web server isn’t required to host the app. Serverless deployment scenarios are possible (for example, serving the app from a CDN).

There are downsides to Blazor WebAssembly hosting:

  • The app is restricted to the capabilities of the browser.
  • Capable client hardware and software (for example, WebAssembly support) is required.
  • Download size is larger, and apps take longer to load.
  • .NET runtime and tooling support is less mature. For example, limitations exist in .NET Standard support and debugging.

Another way to host a Blazor app is on server:

Server hosting

The app is executed on the server from within an ASP.NET Core app.

I will try to be as clear as possible here: imagine a view with an input number and a button. When a user click the button, the value of the input should be incremented by one. How to accomplish this task normally?

  • Using javascript
  • Putting input and button in a form and posting data
  • With Blazor, just adding the @onclick directive :)
<input value="@currentCount"/></p><button class="btn btn-primary" @onclick="IncrementCount">Click me</button>@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}

Blazor will create a handler on button click in javascript that will execute the code server side that will increment and return the updated value to the UI that is refreshed. Simple true?

This is the how the process works like:

Blazor process workflow

The Blazor Server hosting model offers several benefits:

  • Download size is significantly smaller than a Blazor WebAssembly app, and the app loads much faster.
  • The app takes full advantage of server capabilities, including use of any .NET Core compatible APIs.
  • .NET Core on the server is used to run the app, so existing .NET tooling, such as debugging, works as expected.
  • Thin clients are supported. For example, Blazor Server apps work with browsers that don’t support WebAssembly and on resource-constrained devices.
  • The app’s .NET/C# code base, including the app’s component code, isn’t served to clients.

There are downsides to Blazor Server hosting:

  • Higher latency usually exists. Every user interaction involves a network hop.
  • There’s no offline support. If the client connection fails, the app stops working.
  • Scalability is challenging for apps with many users. The server must manage multiple client connections and handle client state.
  • An ASP.NET Core server is required to serve the app. Serverless deployment scenarios aren’t possible (for example, serving the app from a CDN).

The Webassembly hosting model actually is on preview with .Net Core 3.1, instead Server hosting model is already available in .Net core 3.0.

Blazor Components

Blazor apps are built using components. A component is a self-contained chunk of user interface (UI), such as a page, dialog, or form. A component includes HTML markup and the processing logic required to inject data or respond to UI events. Components are flexible and lightweight. They can be nested, reused, and shared among projects.

Members of the component class are defined in an @code block. In the @code block, component state (properties, fields) is specified with methods for event handling or for defining other component logic.

Component members can be used as part of the component’s rendering logic using C# expressions that start with @.

<h1 style="font-style:@_headingFontStyle">@_headingText</h1>@code{
private string _headingText = "Hello!";
private string _headingFontStyle= "italic";
}

After the component is initially rendered, the component regenerates its render tree in response to events. Blazor then compares the new render tree against the previous one and applies any modifications to the browser’s Document Object Model (DOM).

A component can be used in a UI composition flow just defining it in the view parent:

<HeadingComponent />

Blazor JavaScript interop

Another nice feature of Blazor is the possibility to call javascript function from server side code and viceversa.

From .NET to JS

To call into JavaScript from .NET, use the IJSRuntime abstraction. The InvokeAsync<T> method takes an identifier for the JavaScript function that you wish to invoke along with any number of JSON-serializable arguments. The function identifier is relative to the global scope (window). If you wish to call window.someScope.someFunction, the identifier is someScope.someFunction. There's no need to register the function before it's called. The return type T must also be JSON serializable.

For example if you have a javascript code like this:

window.convertArray = (win1251Array) => {
var win1251decoder = new TextDecoder('windows-1251');
var bytes = new Uint8Array(win1251Array);
var decodedArray = win1251decoder.decode(bytes);
console.log(decodedArray);
return decodedArray;
};

Can be called from server side code in javascript using this code:

private uint[] QuoteArray = new uint[] { 60, 101, 109, 62, 67, 97, 110};var text = await JSRuntime.InvokeAsync<string>("convertArray", QuoteArray);

The result is retrieved calling the javascript function.

From JS to .NET

Instead, to invoke a static .NET method from JavaScript, use the DotNet.invokeMethod or DotNet.invokeMethodAsync functions. Pass in the identifier of the static method you wish to call, the name of the assembly containing the function, and any arguments. To invoke a .NET method from JavaScript, the .NET method must be public, static, and have the [JSInvokable] attribute. By default, the method identifier is the method name, but you can specify a different identifier using the JSInvokableAttribute constructor. Calling open generic methods isn't currently supported.

This is an example.

The method ReturnArrayAsync (the server side code in Blazor must be in @code section) is decorated with JSInvokable attribute and is public and static.

@code {     
[JSInvokable]
public static Task<int[]> ReturnArrayAsync()
{
return Task.FromResult(new int[] { 1, 2, 3 });
}
}

Javascript code that call above method is the follow:

DotNet.invokeMethodAsync('BlazorSample','ReturnArrayAsync')
.then(data => { data.push(4);
console.log(data);}
);

Conclusion

Blazor is awesome. It allows the development of applications with a rich interface, speeding up the implementation and design. It presents itself as an alternative to the various Angular, React, VueJS, orienting itself towards Microsoft developers who also want the UI to remain in the .NET ecosystem. Synergic integration with SignalR allows applications developed with Blazor to have a very pleasant user experience. Future development, but not so remote, in WebAssembly optics opens the door to a new way of conceiving web development.

This are the resources used by me to learn Blazor and begin to use in my projects:

--

--

Nicola Sante Dipierro

Solution Architect and Technical Project Manager with Full Stack Developer background. Passionate about not making same mistakes twice. Only new mistakes!