DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Build a Simple Chat Server With gRPC in .Net Core
  • An Introduction to Type Safety in JavaScript With Prisma
  • TestCafe Integration With Cucumber
  • How to Create a Nested Grid Using Angular 8

Trending

  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • Efficient API Communication With Spring WebClient
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • The Evolution of Scalable and Resilient Container Infrastructure
  1. DZone
  2. Coding
  3. Languages
  4. JavaScript Interop in Blazor

JavaScript Interop in Blazor

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

By 
Ankit Sharma user avatar
Ankit Sharma
·
Updated Jun. 18, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
12.0K Views

Join the DZone community and get the full member experience.

Join For Free

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 possible 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 to 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, 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 on our machine.

Open the folder you want to create your project in. Open Windows PowerShell by pressing 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 the Solution Explorer, as shown in the below image.

We will add our Razor page in the Pages folder.

Create a new file by right-clicking on the Pages folder and select New File. Name the file 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 Page folder will have the following structure.

Calling a JavaScript Function From C#

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

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
    <title>BlazorJSDemo</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/site.css" rel="stylesheet" />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>

<body>
    <app>Loading...</app>

    <script type="blazor-boot"></script>

    <script>
        Blazor.registerFunction('JSMethod', function () {
            $("#demop").text("JavaScript Method invoked");
        });
    </script>
</body>

</html>

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

Inside the <body> section, we are registering the function on the JavaScript side using Blazor.registerFunction. The function name is JSMethod and it is not accepting any arguments. When triggered, it will set the text of a <p> tag, which has the id "demop," to "JavaScript Method invoked."

Important Note

Do not write your JS code in the .cshtml file. This is not allowed in Blazor and the compiler will throw an error.

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

using Microsoft.AspNetCore.Blazor.Browser.Interop;
using Microsoft.AspNetCore.Blazor.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlazorJSDemo.Pages
{
    public class JSDemoModel : BlazorComponent
    {
        protected void CallJSMethod()
        {
            RegisteredFunction.Invoke<bool>("JSMethod");
        }
    }
}

The method CallJSMethod will call our JS function "JSMethod" by using "RegisteredFunction.Invoke." RegisteredFunction.Invoke can take two parameters - the registered JS function name and any parameter that needed to be supplied to the JS function. In this case, we are not passing any parameters to the JS function.

Open JSDemo.cshtml and put in the following code:

@page "/demo"
@using BlazorJSDemo.Pages

@inherits JSDemoModel  

<h1>JavaScript Interop Demo</h1>

<hr />

<button class="btn btn-primary" onclick="@CallJSMethod">Call JS Method</button>

<br />
<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 the base URL then we will be redirected to this page. We are also inheriting the JSDemoModel class, which is defined in the JSDemo.cshtml.cs file. This will allow us to use the methods defined in the JSDemoModel class.

After this, we have defined a button. This button will invoke the CallJSMethod method when clicked. The <p> element with an id of "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 the wwwroot/index.html file, which will call our C# method in the JSDemo.cshtml.cs file.

The syntax of calling a C# method from JavaScript is as follows:

Blazor.invokeDotNetMethod({
     type: {
         assembly: 'the assembly name of C# method',
         name: 'namespace.classname of C# method'

     },
     method: {
         name: 'C# method name'
     }
 })

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

<script>
     Blazor.registerFunction('CSMethod', function () {
         Blazor.invokeDotNetMethod({
             type: {
                 assembly: 'BlazorJSDemo',
                 name: 'BlazorJSDemo.Pages.JSDemoModel'

             },
             method: {
                 name: 'CSCallBackMethod'
             }
         })
     });
 </script>

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

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

  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.

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

protected static string message { get; set; }

public static void CSCallBackMethod()
{
    message = "C# Method invoked";
}

protected void CallCSMethod()
{
    RegisteredFunction.Invoke<bool>("CSMethod");
}

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 the JavaScript function CSMethod. This will set the value of a string variable message, which will be displayed on the UI.

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

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

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

Adding Links to the Navigation Menu

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

<div class="top-row pl-4 navbar navbar-dark">
    <a class="navbar-brand" href="">BlazorJSDemo</a>
    <button class="navbar-toggler" onclick=@ToggleNavMenu>
        <span class="navbar-toggler-icon"></span>
    </button>
</div>

<div class=@(collapseNavMenu ? "collapse" : null) onclick=@ToggleNavMenu>
    <ul class="nav flex-column">
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="" Match=NavLinkMatch.All>
                <span class="oi oi-home" aria-hidden="true"></span> Home
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="counter">
                <span class="oi oi-plus" aria-hidden="true"></span> Counter
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="fetchdata">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
            </NavLink>
        </li>
         <li class="nav-item px-3">
            <NavLink class="nav-link" href="demo">
                <span class="oi oi-list-rich" aria-hidden="true"></span> JS Demo
            </NavLink>
        </li>
    </ul>
</div>

@functions {
    bool collapseNavMenu = true;

    void ToggleNavMenu()
    {
        collapseNavMenu = !collapseNavMenu;
    }
}

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 the JSdemo view. 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 the Blazor framework.

You can get the source code from GitHub and play around to get a better understanding.

See Also

  • ASP.NET Core – Getting Started With Blazor
  • ASP.NET Core – CRUD Using Blazor And Entity Framework Core
  • Creating an SPA Using Razor Pages With Blazor
  • Cascading DropDownList In Blazor Using EF Core
  • Deploying A Blazor Application On IIS
Blazor JavaScript application Entity Framework .NET Visual Studio Code

Published at DZone with permission of Ankit Sharma, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Build a Simple Chat Server With gRPC in .Net Core
  • An Introduction to Type Safety in JavaScript With Prisma
  • TestCafe Integration With Cucumber
  • How to Create a Nested Grid Using Angular 8

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!