Blazor, JavaScript, and Interpolation

ASP.NET Blazor is a free and open-source web framework developed by Microsoft that allows you to build interactive web UIs with C# and HTML. It is a component-based framework, where a component is a way to encapsulate reusable UI elements, making it easier to structure and maintain your applications.

The main selling point of the ASP.NET Blazor framework is its ability to build rich web applications using C# instead of JavaScript, significantly simplifying development for .NET developers.

But, is Blazor meant to replace JavaScript entirely, or does it have a different role?

First of all, when you talk about the web, you think about HTML, CSS, and JavaScript. These technologies form the core of front-end web development, with JavaScript being essential for dynamic and interactive elements. While Blazor offers a compelling alternative by allowing developers to use C# and .NET, JavaScript has a vast ecosystem, widespread community support, and a lot of proven libraries and frameworks. So, beating JavaScript on the web is incredibly difficult, if not impossible.

Secondly, Blazor isn’t designed as a wholesale replacement for JavaScript. It provides a powerful alternative for developers who are more comfortable with .NET technologies. In many scenarios, Blazor and JavaScript can work together. Blazor components can leverage existing JavaScript libraries when needed.

The process of enabling interaction between JavaScript and C# code in ASP.NET Blazor applications is referred to as JavaScript interoperability.

This capability strategically overcomes potential limitations in Blazor, including:

  • Limited Browser APIs: While Blazor offers its own set of APIs, it cannot directly access all native browser functionalities. JavaScript interop acts as a bridge, allowing C# code to interact with essential browser APIs like geolocation, camera access, and offline storage.
  • Legacy JavaScript Ecosystem: The web has already an established ecosystem of JavaScript libraries and frameworks. Without interoperability, Blazor apps would be limited to functionalities developed solely within the Blazor framework. This would significantly restrict the range of features and functionalities available to developers.
  • Advanced UI Interactions: While Blazor’s component model offers powerful UI creation capabilities, some complex interactions might require direct DOM manipulation. JavaScript interop allows developers to leverage the full potential of the DOM for specific UI needs.
  • Performance Optimization: In specific cases, leveraging optimized JavaScript libraries can significantly improve the performance of certain tasks within a Blazor app. JavaScript interop allows developers to offload such tasks to JavaScript code, leading to improved responsiveness and user experience.

JavaScript interoperability is a powerful tool, but it’s best used strategically. Relying too heavily on it can reduce the benefits of using Blazor in the first place. Also, while Blazor WebAssembly itself often reduces the need for JavaScript interpolation, it remains valuable for accessing browser-specific APIs and taking advantage of the many existing JavaScript libraries.

Collaboration and Separation of JavaScript and C#

JavaScript and C# can work together smoothly in Blazor apps. Blazor lets you call JavaScript code from C#, and C# code from JavaScript, making it simple to combine their strengths. You can use JavaScript to create custom, interactive parts of your Blazor website’s interface and take advantage of the many great JavaScript libraries available.

Blazor WebAssembly enables .NET code to run in the browser, similar to JavaScript. This simplifies things because you don’t need separate tools or systems to make everything function.

However,

C# is still your go-to language for building the core parts of Blazor apps. C# offers advantages like clear type definitions, object-oriented design, and powerful development tools. Even when using WebAssembly, Blazor creates a separate space for your .NET code to run. This keeps things organized and prevents conflicts between JavaScript and C#.

The way you write code in JavaScript and C# differs. JavaScript is more flexible and free-flowing, while C# prefers order and specific rules. This means you may need to write code differently depending on the language you’re using.

Now, let’s have a look at some code examples of how you can use JavaScript interpolation.

Ex: Calling JavaScript from C#

The code below demonstrates how a C# method can call a JavaScript function within a Blazor component.

<button @onclick="ShowAlert">Show Alert</button>


@code {

    private void ShowAlert()

    {

        JSRuntime.InvokeVoidAsync("alert", "Hello from Blazor!");

    }

}

How does this code work?

<button @onclick="ShowAlert">Show Alert</button>

This is the HTML markup for a button element. @onclick is a Blazor directive that binds a C# method named ShowAlert to the button’s click event.

@code { ... }

This denotes a Blazor code block where you define C# logic for your component. ShowAlert() is a private C# method called which will be executed when the button is clicked.

JSRuntime.InvokeVoidAsync("alert", "Hello from Blazor!");

JSRutime is an ASP.NET Blazor service that allows you to interact with JavaScript from C#. It uses the InvokeVoidAsync method to execute the JavaScript function asynchronously. It takes as the first parameter the name of the function and the other parameters are the inputs of the function. In this case, the alert has a single parameter, but if it would have had more than one, then you can just pass them after the first parameter using double quotes.

Alert doesn’t return a value, it is the default JavaScript function to display an alert box. That is why we have used the InvokeVoidAsyc method instead of InvokeAsync<T>.

So, when the user clicks the “Show Alert” button, it triggers the browser to display a pop-up alert box containing the message “Hello from Blazor!”.

Ex: Calling C# from JavaScript

The code below demonstrates how a JavaScript function can call a C# method within a Blazor component.

<button @onclick="callDotNetMethod">Show Alert</button>

@code {

    [JSInvokable]

    public static Task UpdateMessageFromJS()

    {

         Console.WriteLine($"Message from JS");

         return Task.CompletedTask;

    }

}

[JSInvokable] is a must-have attribute for a C# method that will be called from JavaScript. The UpdateMessageFromJS() method is the C# method that will be invoked by JavaScript. It does not do anything, it just writes the received message to the browser’s console. Task.CompletedTask indicates the task is completed.

function callDotNetMethod() {

    DotNet.invokeMethodAsync(‘_AssemblyName_', 'UpdateMessageFromJS', 'Hello from JavaScript!')

        .then(data => {

            console.log(data);

        });

}

callDotNetMethod() { ... } defines the JavaScript function that will initiate the call to the C# method.

DotNet.invokeMethodAsync(‘_AssemblyName_', 'UpdateMessageFromJS', 'Hello from JavaScript!')

DotNet is a JavaScript object exposed by Blazor for interoperability. invokeMethodAsync is a function to call a .NET method from JavaScript asynchronously. '_AssemblyName_' is a placeholder of your actual Blazor assembly. 'UpdateMessageFromJS' is the name of the C# method to be called and to this method as an argument we are passing ‘Hello from JavaScript’ text.

So, when the user clicks the button, it triggers the JavaScript function callDotNetMethod. This function then uses DotNet.invokeMethodAsync to call the C# method UpdateMessageFromJS, sending the message “Hello from JavaScript!”. The C# method receives the message, writes it to the console, and returns a completed task to signal successful execution.

Where to go next?

If you wat to learn more I have created a tutorial on Pluralsight which teaches you all you need to know to get started with JavaScript interpolation in ASP.NET Blazor.

JavaScript Interop in ASP.NET Core Blazor [Pluralsight]
Intro of the “JavaScript Interop in ASP.NET Core Blazor” course at PluralSight

Check out the full course here: https://bit.ly/3wvcl8g


Enjoyed this post? Subscribe to my YouTube channel for more great content. Your support is much appreciated. Thank you!


Check out my Udemy profile for more great content and exclusive learning resources! Thank you for your support.
Ervis Trupja - Udemy



Enjoyed this blog post? Share it with your friends and help spread the word! Don't keep all this knowledge to yourself.