Book Image

Blazor WebAssembly by Example

By : Toi B. Wright
Book Image

Blazor WebAssembly by Example

By: Toi B. Wright

Overview of this book

Blazor WebAssembly makes it possible to run C# code on the browser instead of having to use JavaScript, and does not rely on plugins or add-ons. The only technical requirement for using Blazor WebAssembly is a browser that supports WebAssembly, which, as of today, all modern browsers do. Blazor WebAssembly by Example is a project-based guide for learning how to build single-page web applications using the Blazor WebAssembly framework. This book emphasizes the practical over the theoretical by providing detailed step-by-step instructions for each project. You'll start by building simple standalone web applications and progress to developing more advanced hosted web applications with SQL Server backends. Each project covers a different aspect of the Blazor WebAssembly ecosystem, such as Razor components, JavaScript interop, event handling, application state, and dependency injection. The book is designed in such a way that you can complete the projects in any order. By the end of this book, you will have experience building a wide variety of single-page web applications with .NET, Blazor WebAssembly, and C#.
Table of Contents (11 chapters)

Exploring JS interop

To invoke a JavaScript function from .NET, we use the IJSRuntime abstraction. This abstraction represents an instance of a JavaScript runtime that the framework can call into. To use IJSRuntime, we must first inject it into our component using dependency injection. For more information on dependency injection, refer to Chapter 6, Building a Shopping Cart Using Application State.

The @inject directive is used to inject a dependency into a component. The following code injects IJSRuntime into the current component:

@inject IJSRuntime js

The IJSRuntime abstraction has two methods that we can use to invoke JavaScript functions:

  • InvokeVoidAsync
  • InvokeAsync

Both of these methods are asynchronous. The difference between these two methods is that one of them returns a value and the other does not. We can downcast an instance of IJSRuntime to an instance of IJSInProcessRuntime to run the method synchronously. Finally, we can invoke a .NET method...