Book Image

Blazor WebAssembly by Example, 2e - Second Edition

By : Toi B. Wright
5 (1)
Book Image

Blazor WebAssembly by Example, 2e - Second Edition

5 (1)
By: Toi B. Wright

Overview of this book

Blazor WebAssembly helps developers build web applications without the need for JavaScript, plugins, or add-ons. With its continued growth in popularity, getting started with Blazor now can open doors to new career paths and exciting projects – and Blazor WebAssembly by Example will make your first steps easier. This is a project-based guide that will teach you how to build single-page web applications with Blazor, focusing heavily on the practical over the theoretical by providing detailed step-by-step instructions for each project. The author also includes a video for each project showing her following the step-by-step instructions, so readers can use them if they're unsure about any particular step. In this updated edition, you'll start by building simple standalone web applications and gradually progress to developing more advanced hosted web applications with SQL Server backends. Each project will cover a different aspect of the Blazor WebAssembly ecosystem, such as Razor components, JavaScript interop, security, event handling, debugging on the client, application state, and dependency injection. The book’s projects get more challenging as you progress, but you don’t have to complete them in order, which makes this book a valuable resource for beginners as well as those who just want to dip into specific topics. By the end of this book, you will have experience and lots of know-how on how to build a wide variety of single-page web applications with .NET, Blazor WebAssembly, and C#.
Table of Contents (15 chapters)
13
Other Books You May Enjoy
14
Index

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 7, 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:

  • InvokeAsync
  • InvokeVoidAsync

Both 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 from JavaScript by decorating the...