JavaScript Interop In Blazor

Introduction

In this article, we will learn about JavaScript Interop in Blazor. We will understand what JavaScript Interop is and how we can implement it in Blazor with the help of a sample application.

We will be using Visual Studio code for our demo.

What is JavaScript Interop?

Blazor uses JavaScript to bootstrap the .NET runtime. It is capable to use any JS library. C# code can call a JS function/API and JS code can call any C# methods. This property of calling a JS method from C# code and vice versa is referred as JavaScript Interop. Blazor uses JavaScript Interop to handle DOM manipulation and browser API calls.

JavaScript Interop is the feature provided by WebAssembly. Since Blazor runs on Mono and mono is compiled to WebAssembly. Hence, Blazor can also implement this feature.

Prerequisites

  • Install the .NET Core 2.1 or above SDK from here.
  • Install visual Studio Code from here.

Source Code

Get the source code from Github.

Creating the Blazor application

We will create a Blazor application using windows PowerShell.

Step 1

First, we will install the Blazor framework templates in our machine,

Open the folder where you want to create your project. Open Windows PowerShell by doing shift + right click >> Open PowerShell window Here.

Type in the following command

  • dotnet new -i Microsoft.AspNetCore.Blazor.Templates
Refer to the image below,

 

Step 2

Type in the following command to create our Blazor application.

  • dotnet new blazor -o BlazorJSDemo
This will create a Blazor application with name BlazorJSDemo. Refer to the image below.
 
 

Adding Razor Page to our application

Open the BlazorJSDemo app using VS code. You can observe the folder structure in Solution Explorer, as shown in the below image.

 

We will add our Razor page in Pages folder.

Create a new file by right clicking on Pages folder and select New File. Name the file as JSDemo.cshtml. This file will contain HTML code to handle the UI of our application.

Similarly, add one more file JSDemo.cshtml.cs. This file will contain the C# code to handle our business logic.

Now our Pages folder will have the following structure.

 
Calling a JavaScript function from C#

First, we will write our JavaScript functions in index.html file. Open wwwroot/index.html file and put in the following code.

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <meta name="viewport" content="width=device-width">  
  7.     <title>BlazorJSDemo</title>  
  8.     <base href="/" />  
  9.     <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />  
  10.     <link href="css/site.css" rel="stylesheet" />  
  11.   
  12.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
  13.   
  14. </head>  
  15.   
  16. <body>  
  17.     <app>Loading...</app>  
  18.   
  19.     <script src="_framework/blazor.webassembly.js"></script>  
  20.   
  21.     <script>  
  22.         function JSMethod() {  
  23.             $("#demop").text("JavaScript Method invoked");  
  24.         }  
  25.     </script>  
  26.   
  27. </body>  
  28.   
  29. </html>  

Here we have included the CDN reference to JQuery library inside <head> section so that we can handle the DOM manipulation.

Inside the <body> section, we have defined our JS function. The function name is JSMethod and it is not accepting any arguments. When triggered it will set the text of a <p> tag having id “demop” to “JavaScript Method invoked”. 

Important Note

  1. Do not write your JS code in .cshtml file. This is not allowed in Blazor and the compiler will throw an error. Always put your JS code in wwwroot/index.html file.
  2. Always add your custom <script> tag after “<script src=”_framework/blazor.webassembly.js”></script>” in the <body> section of index.html file. This is to ensure that your custom script will execute after loading of “blazor.webassembly.js” script.

Open JSDemo.cshtml.cs and put in the following code,

  1. using Microsoft.AspNetCore.Blazor.Components;  
  2. using Microsoft.JSInterop;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace BlazorJSDemo.Pages  
  9. {  
  10.     public class JSDemoModel : BlazorComponent  
  11.     {  
  12.         protected static string message { getset; }  
  13.   
  14.         protected void CallJSMethod()  
  15.         {  
  16.             JSRuntime.Current.InvokeAsync<bool>("JSMethod");  
  17.         }  
  18.     }  
  19. }   

The method CallJSMethod will call our JS function “JSMethod” by using “JSRuntime.Current.InvokeAsync” method. This method can take two parameters – the JS function name and any parameter that needed to be supplied to the JS function. In this case, we are not passing any parameter to JS function.

Open JSDemo.cshtml and put in the following code,

  1. @page "/demo"  
  2. @using BlazorJSDemo.Pages  
  3.   
  4. @inherits JSDemoModel    
  5.   
  6. <h1>JavaScript Interop Demo</h1>  
  7.   
  8. <hr />  
  9.   
  10. <button class="btn btn-primary" onclick="@CallJSMethod">Call JS Method</button>  
  11.   
  12. <br />  
  13. <p id="demop"></p>  

Here we have defined the route of the page at the top. So, in this application, if we append “/demo” to base URL then we will be redirected to this page. We are also inheriting JSDemoModel class, which is defined in JSDemo.cshtml.cs file. This will allow us to use the methods defined in JSDemoModel class.

After this, we have defined a button. This button will invoke “CallJSMethod” method when clicked. The <p> element with id “demop” is also defined and its value will be set by the JS function “JSMethod”. 

Calling a C#/.NET method from JavaScript

Now we will define our JS Method in wwwroot/index.html file, which will call our C# method in JSDemo.cshtml.cs file.

The syntax of calling a C# method from JavaScript is as follows,
  1. DotNet.invokeMethodAsync('C# method assembly name''C# Method Name');   

Therefore, we will follow the same method calling syntax. Open wwwroot/index.html file and add the following script section to it.

  1. <script>  
  2.   function CSMethod() {  
  3.     DotNet.invokeMethodAsync('BlazorJSDemo''CSCallBackMethod');  
  4.   }  
  5. </script>   

Here we are defining a JS function “CSMethod”. This function will have a call back to our C# method “CSCallBackMethod” which is defined in JSDemoModel class.

To invoke a C#/.NET method from JavaScript the target .NET method must meet the following criterias:

  1. The method needs to be Static.
  2. It must be Non-generic.
  3. The method should have no overloads.
  4. It has concrete JSON serializable parameter types.
  5. It must be decorated with [JSInvokable] attribute.

Open JSDemo.cshtml.cs file and add the following code inside JSDemoModel class.

  1. protected static string message { getset; }  
  2.   
  3. [JSInvokable]  
  4. public static void CSCallBackMethod()  
  5. {  
  6.   message = "C# Method invoked";  
  7. }  
  8.   
  9. protected void CallCSMethod()  
  10. {  
  11.   JSRuntime.Current.InvokeAsync<bool>("CSMethod");  
  12. }   

Here we have defined two methods,

  1. CallCSMethod :- This will call our JS function “CSMethod”
  2. CSCallBackMethod: – This is a static method and it will be invoked from JavaScript function “CSMethod”. Hence it is decorated with [JSInvokable] attribute. This method will set the value of a string variable message, which will be displayed on the UI.

Open JSDemo.cshtml file and add the following code to it.

  1. <button class="btn btn-primary" onclick="@CallCSMethod">Call C# Method</button>  
  2. <br />  
  3. <p>@message</p>  

Here we have defined a button which will call “CallCSMethod” method on the "onclick" event. The value of variable message is set on the button click.

Adding Link to Navigation menu

Open \BlazorJSDemo\Shared\NavMenu.cshtml page and put the following code into it. This will include a link to our JSDemo.cshtml page in the navigation menu.

  1. <div class="top-row pl-4 navbar navbar-dark">  
  2.     <a class="navbar-brand" href="">BlazorJSDemo</a>  
  3.     <button class="navbar-toggler" onclick=@ToggleNavMenu>  
  4.         <span class="navbar-toggler-icon"></span>  
  5.     </button>  
  6. </div>  
  7.   
  8. <div class=@(collapseNavMenu ? "collapse" : null) onclick=@ToggleNavMenu>  
  9.     <ul class="nav flex-column">  
  10.         <li class="nav-item px-3">  
  11.             <NavLink class="nav-link" href="" Match=NavLinkMatch.All>  
  12.                 <span class="oi oi-home" aria-hidden="true"></span> Home  
  13.             </NavLink>  
  14.         </li>  
  15.         <li class="nav-item px-3">  
  16.             <NavLink class="nav-link" href="counter">  
  17.                 <span class="oi oi-plus" aria-hidden="true"></span> Counter  
  18.             </NavLink>  
  19.         </li>  
  20.         <li class="nav-item px-3">  
  21.             <NavLink class="nav-link" href="fetchdata">  
  22.                 <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data  
  23.             </NavLink>  
  24.         </li>  
  25.          <li class="nav-item px-3">  
  26.             <NavLink class="nav-link" href="demo">  
  27.                 <span class="oi oi-list-rich" aria-hidden="true"></span> JS Demo  
  28.             </NavLink>  
  29.         </li>  
  30.     </ul>  
  31. </div>  
  32.   
  33. @functions {  
  34.     bool collapseNavMenu = true;  
  35.   
  36.     void ToggleNavMenu()  
  37.     {  
  38.         collapseNavMenu = !collapseNavMenu;  
  39.     }  
  40. }  

Execution demo

Navigate to View >> Integrated Terminal to open the terminal window.

Type the command dotnet run to start the application. Refer to the image below:

 

You can observe that the application is listening on http://localhost:5000. Open any browser on your machine and navigate to this URL.

You can see the application home page. Click on the “JS Demo” link in the navigation menu to open JSdemo view. Notice the URL has “/demo” appended to it.

Click on the buttons to invoke JS functions and C# method.

Refer to the GIF image below. 

 

Conclusion

We have learned about JavaScript Interop. We have also created a sample application to demonstrate how JavaScript Interop works with Blazor framework.

Please get the source code from Github and play around to get a better understanding.

You can also read other articles on my personal blog here

See Also


Similar Articles