Interact With Javascript In Blazor App

Introduction

As we all know, Blazor is a web framework that enables developers to create web apps using C# instead of JavaScript. But let's not get carried away. No app is truly a web app unless JavaScript has its say in it. 

When it comes to Blazor there is one buzzword that goes around, i.e. JavaScript Interoperability or JS interop for short. It simply means the ability to call JS functions using C# and vice-versa. 

Let me teach you step by step.

Step 1 - Create a razor component

For a demo, Let's design a page to invite Alex to the party. I am creating a web-assembly app. and I've added a razor component named "BlazingJS.razor"

This page has a button with an onclick-event which is handled by a method named "InvitaionToTheParty()". Nothing fancy so far.

@page "/blazingJS"

<div> 
    <button class="btn btn-secondary" @onclick="InvitaionToTheParty"> Invite Alex </button>
</div>

@code {
    private async Task InvitaionToTheParty(){ }
}

Listing 1: BlazingJS.razor

Step 2 - Inject JavaScript 

Interface IJSRuntime represents an instance of a JavaScript runtime, it is used to handle DOM manipulation and API calls.

@inject IJSRuntime JsRuntime;

Listing 2: Injecting JsRuntime in razor component.

IJSRuntime exposes us to 2 methods, 

  1. InvokeVoidAsync(): This method does not return anything.
  2. InvokeAsync(): Returns some value

In our example, we are going with InvokeAsync() as we are going to return a boolean value.

Step 3 - Call a confirm box using JsRuntime

Confirm box has 2 buttons, "Okay" and "Cancel". If the user clicks on Okay button JS will return true and if the user clicks on the cancel button JS will return false.

Let's store this boolean result in property called "IsConfirmed " (Listing 3 - Line number 5).

InvokeAsync takes 2 parameters (Listing 3 - Line number 7):

  1. Name of the function that is supposed to be called, which is "confirm" in our case.
  2. The message that we want to show on the confirmation box.

Note: we are defining a return type boolean while invoking a method, For which we need to use method signature as InvokeAsync<bool>

@code {

    public bool IsConfirmed { get; set; }

    private async Task InvitaionToTheParty()
    {
        IsConfirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Alex, are you coming to the party?");
    }
}

Listing 3: Calling InvokeAsync method

Step 4 - Little bit of HTML

In Listing 4, I am using a button with some bootstrap classes and an "onclick-event".

Followed by C# code which toggles the message on UI. 

Finally, Some minor styles for messages.

<div>    
    <button class="btn btn-secondary" @onclick="InvitaionToTheParty"> Invite Alex</button>
</div>
<br />
<div>
    @if (IsConfirmed)
    {
        <span class="label success"> Alex, is coming to the Party! </span>
    }
    else
    {
        <span class="label warning"> Alex, is yet to respond! </span>
    }
</div>

<style>
    .label {
        color: white;
        padding: 8px;
    }

    .success {
        background-color: #04AA6D;
    }

    .warning {
        background-color: #ff9800;
    }
</style>

Listing 4: HTML for BlazingJS.razor

The Output

In the following gif, you can see how the confirmation box is getting popped up on the top of the screen. It has 2 buttons, "Okay" and "Cancel" and based on button's click the label is being changed.

Gif 1: Output

Conclusion

This is how you can use JavaScript runtime in .Net to call JS functions through razor components. There is a lot we can do with JavaScript, in upcoming articles I'll try to unleash the potential of JS Interop.


Similar Articles