JavaScript Interoperability in Blazor

JavaScript Interoperability in Blazor

This blog is going to explain JavaScript Interoperability in Blazor. Sometimes it is necessary to use JavaScript in Blazor; you can not avoid that. To use the JavaScript in Blazor, you have to use the IJSRuntime instance via the dependency injection. The InvokeAsync method helps to call the JavaScript function.

Let's see how to use JavaScript in Blazor.

Step1: Create a new Blazor WebAssembly App
In Visual Studio -> Create a New Project -> Blazor App. Provide Project name and Location. Then click the Create button. It will display the Create a New Blazor app window. In there, select 'Blazor WebAssembly App';
Blazor WebAssembly App

Step 2: Create JavaScript File
In this step I have created a javascript file with the name SampleJavaScript.js, under wwwroot -> Scripts folder. The following is a code of simple javascript code for adding two integer numbers.

\wwwroot\Scripts\SampleJavaScript.js
function CalulateSum(firstValue, secondValue) {
    alert(firstValue + secondValue);
}

Step 3: JavaScript reference
In this step, I have added the JavaScript reference to the application. For that, I included the javascript reference to the index.html page.

\wwwroot\index.html
<body>
    <app>Loading...</app>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss">🗙</a>
    </div>
    <script src="_framework/blazor.webassembly.js"></script>
    <script src="Scripts/SampleJavaScript.js"></script>
</body>

Step 4: Calculate Page
The following is a calculate page code. Here I have injected the IJSRuntime instence using @inject directive. And added two textbox to collect the input value and one button to display the calculated value. Using InvokeVoidAsync() method I have called the CalulateSum Javacript method and pass the input value.

\Pages\Calculate.razor
@page "/calculate"

@inject IJSRuntime jsRuntime

<h4>JavaScript Interoperability in Blazor</h4>
<br />
<br />
First Value:
<input @bind="firstValue" />
<br />
<br />
Second Value:
<input @bind="secondValue" />
<br />
<br />
<button type="button" class="btn btn-info" @onclick="ShowSum">Sum</button>

@code {
    private int firstValue;
    private int secondValue;

    public async Task ShowSum()
    {
        await jsRuntime.InvokeVoidAsync("CalulateSum", firstValue, secondValue);
    }
}

Output
The following is an output of the above code. Here you can see when the user clicks on the sum button, it gives the result in JavaScript alert message.

JavaScript Interoperability in Blazor

I hope this helps you. Keep coding.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

SignalR with JavaScript in ASP.NET Core MVC

Localization in ASP.NET Core MVC with Example