.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa

Blazor is an open source and cross-platform web UI framework for building single-page apps using .NET and C# instead of JavaScript. Blazor is based on a powerful and flexible component model for building rich interactive web UI.
 
Please read my article on Blazor Introduction - Blazor - C# In Browser
 
Blazor WebAssembly includes a proper .NET runtime implemented in WebAssembly, a standardized bytecode for the web. This .NET runtime is downloaded with your Blazor WebAssembly app and enables running normal .NET code directly in the browser. No plugins or code transpilation are required. Blazor WebAssembly works with all modern web browsers, both desktop and mobile.
 
Without the need of JavaScript, developers can build a full stack web application using C#, HTML & CSS. But there are situations where developers need to communicate with an existing JavaScript library. In this article I am going to explain how to call JavaScript from C# in Blazor WebAssembly & vice versa.
 
Let’s create a sample Blazor WebAssembly app using Visual Studio 2019.
 
As a first step open visual studio 2019 ->create new project -> select Blazor WebAssembly template with .Net 5 as target runtime, give a project name and click create.
 
In the solution explorer, you can see a default project template with some components. Under the pages folder you can see there is a Counter.razor component. If we open that, you can see that the HTML and the C# code is tied together. I am not a big fan of this approach hence I am splitting the C# code from the html. In order to achieve that, right click on the pages folder and create a new class named Counter.razor.cs and make the class a partial class. Move C# code from Counter.razor file and paste it in the newly created partial class. Now run the application and see if the counter page is working as expected.
 

Calling JavaScript From C#

 
Step 1
 
Create a JavaScript file named main.js in the wwwroot folder. In the main.js file create two functions. One function accepts a parameter and just simply logs the counter value to a console and the other method return a string message.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 2
 
Open the index.html file and add a reference to the main.js file in the head tag.
 
Step 3
 
Add a new folder named JSInterop and add a class named JavascriptInvoker.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 4
 
Create an interface named IJavascriptInvoker with two methods.
 
a. Task PrintAsync(int counter);
b. Task PrintGreetingMessageAsync()
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 5
 
Let JavaScriptInvoker class inherit from IJavascriptInvoker and implement the interface. (IJavascriptInvoker interface is placed on top of JavascriptInvoker class).
 
Step 6
 
There is a built-in interface named IJSRuntime which is used to invoke JavaScript methods from C#. This interface is found under the namespace Microsoft.JSInterop. Inject this interface in the constructor.
 
Step 7
 
Inject ILogger interface as well for logging.
 
Step 8
 
There is a method named InvokeVoidAsync in the IJSRuntime interface. This is an overloaded method. The first argument is the name of the JavaScript function and the second argument is the data that we need to pass to the JS function. In our case the first argument value is “printCounter” and the second argument value is the counter variable as shown in figure below. 
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 9
 
Similarly, we need to invoke the getGreetingMessage function in the main.js file. For that we need to change the logic inside the PrintGreetingMessageAsync as shown in figure below.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 10
 
As getGreetingMessage function is returning a string, use the InvokeAsync method of IJSRuntime interface. In the method, mention the name of the of the JavaScript method to be called. In our case it is “getGreetingMessage”.
 
Step 11
 
Open Program.cs file and add the dependency injection for IJavascriptInvoker.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 12
 
Open the Counter.razor.cs file and inject the IJavascriptInvoker interface. Use property injection. Property injecion is achieved by using the Inject attribute.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 13
 
Invoke the PrintAsync and PrintGreetingMessageAsync inside the IncrementCount method as shown. 
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 14
 
Now run the application. Once the application is loaded, open the developer tools and open the console window. Now click on the Counter navigation link and press the Click Me button.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
You can see that both the JavaScript methods are invoked from C# and the output is displayed in the console window.
 

Calling C# Static Methods From JavaScript

 
Step 1
 
Create a static method named LogMessage which returns Task<string> in Counter.razor.cs file.
 
Step 2
 
Decorate the LogMessage function with a [JSInvokable] attribute. This attribute is the namespace Microsoft.JSInterop.
 
Step 3
 
If any function is decorated with JSInvokable attribute, it means that the method can be invoked from JavaScript.
 
Step 4
 
Open the main.js file and create a new function named callCSharpLogMessage as shown in figure.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
You can see that I have used DotNet.invokeMethodAsync method. This is a built-in method in blazor.webassembly.js file. (This JavaScript file is referenced in index.html).
 
Step 5
 
Two parameters are passed in DotNet.invokeMethodAsync function. The first parameter represents the app namespace and the second parameter represents the name of the method in C# file. In our case the first parameter is ‘Blazor.Features’ and the second parameter is the ‘LogMessage’ function.
 
Step 6
 
Now open the Counter.razor page and add a new button as shown in figure.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 7
 
Instead of @onclick, I have used the onclick attribute of button element as we are calling the JavaScript function.
 
Step 8
 
Now run the application and go to the Counter Navigation page and click the Call CSharp Method button and verify the output in the console window of browser.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Now we have successfully invoked a C# static method from JavaScript.
 

Calling C# Instance Methods From JavaScript

 
Calling C# instance methods from JavaScript is not straight forward. In order to achieve it, we have to make some tweaks.
 
Step 1
 
Create a class named DotNetInvoker in the JSInterop Folder.
 
Step 2
 
Inject the IJSRuntime interface in the class constructor.
 
Step 3
 
JavaScript method should first know the reference of the DotNetInvoker class in order to invoke a C# method inside this class.
 
Step 4
 
Create a function named invokeDotNetInstanceFunction in main.js file as shown in figure.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 5
 
invokeDotNetInstanceFunction method accepts one parameter. This parameter accepts the dotnet reference object of DotNetInvoker C# class.
 
Step 6
 
Within the function body, call the invokeMethodAsync method of the referenced class object(dotNetInvoker). invokeMethodAsync is a built-in method of DotNetObjectrReference.
 
Step 7
 
There are 2 parameters passed to invokeMethodAsync. First parameter represents the C# method DisplayCurrentDateAndTime in DotNetInvoker class and the second parameter is a Date object.
 
Step 8
 
Now create a method named Register in DotNetInvoker class file as shown in picture.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
You can see that DotNetObjectReference is used. This class comes under the Microsoft.JSInterop namespace. In the register method assign the objectReference variable as the current class reference (i.e., DotNetInvoker class reference). By using the IJSRuntime interface invoke the ‘invokeDotNetInstanceFunction’ in main.js file and pass the objectReference as input.
 
Step 9
 
Now let’s create a method named DisplayCurrentDateAndTime which accepts a DateTime parameter as input in DotNetInvoker class. Decorate this method with [JSInvokable] attribute.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 10
 
Register the DotNetInvoker class in the services collection in Program.cs.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 11
 
Open Counter.razor.cs file. Inject the DotNetInvoker using Property injection.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 12
 
Add a method named CallInstanceMethod in Counter.razor.cs file.
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 13
 
Invoke the Register method of DotNetInvoker class.
 
Step 14
 
As a final step open the Counter.razor file and add a button. On click of the button it will call the CallInstanceMethod
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
Step 15
 
Now run the application and go to the Counter navigation page and click on the Invoke Instance Method button and verify the output in the console window. 
 
.Net 5 Blazor WASM - Calling JavaScript From C# And Vice Versa
 
So, we have learned how to call JavaScript functions from C# and vice versa. The source code is uploaded for your reference.
 
Happy Coding!!!


Similar Articles