ā¤ļø Blazor + JavaScript: A Perfect Pair For Web Development?


Hey Reader,

Today, I show you how combining Blazor and JavaScript can give you the best of both worlds. Let’s dive into how you can easily mix the power of these two technologies in your projects!

Watch on YouTube šŸ“ŗ

Check out the full tutorial on YouTube to see everything in action šŸ‘‡

video preview​

A Simple Example: Console Logging in Blazor

Imagine you’re working on a Blazor Server application, and you want to log the current count (of the Counter page) to the console.

Your first thought might be to use Console.WriteLine, right? Here’s what that looks like:

Console.WriteLine("Current count is " + currentCount);

This works, but you’ll only see the output in the terminal, not the browser console. But what if you want to log it directly in the browser console? This is where JavaScript comes in handy.

Injecting JavaScript into Blazor

To use JavaScript, you can inject the IJSRuntime interface in your Blazor component and use the InvokeVoidAsync method to call JavaScript functions. Here’s how you do it:

@inject IJSRuntime JS
private async Task LogToConsole()
{
    await JS.InvokeVoidAsync("console.log", "Current count is " + currentCount);
}

When you run this, you’ll see the log directly in your browser’s console. This is a basic example, but you can use this approach to call any JavaScript function from Blazor.

Using Custom JavaScript Files

But what if you want to use your own JavaScript functions? Just create a new JavaScript file in your project’s wwwroot folder. Here’s how:

  1. Create a new folder named js.
  2. Inside it, create a file named myscripts.js.
  3. Add your JavaScript function:
async function log(text) {
    console.log(text);
}

Now, reference this file in your App.razor:

Finally, call this custom function from Blazor:

await JS.InvokeVoidAsync("log", "Using our script, count is " + currentCount);

When you click the button, you’ll see your custom log message in the console.

Logging Complex Objects

Want to log an entire object instead of just a text or value? You can easily do this with JavaScript too. For example, let’s say you have a Player class:

public class Player
{
    public string Name { get; set; } = "Goku";
    public int Level { get; set; } = 9001;
}

You can log this object directly:

var player = new Player();
await JS.InvokeVoidAsync("console.log", player);

JavaScript will display the object in the console, showing all its properties.

Calling Blazor from JavaScript

Sometimes, you might want to call a Blazor function from JavaScript. Although it’s less common, it’s possible! Here’s a quick example:

Create a static Blazor method and mark it with the [JSInvokable] attribute:

[JSInvokable]
public static void IncrementCounter()
{
    currentCount++;
}

In your JavaScript, call this method:

DotNet.invokeMethodAsync('YourAssemblyName', 'IncrementCounter');

When this JavaScript function runs, it calls the Blazor method and increments the counter.

Wrapping Up

Combining Blazor with JavaScript opens up a world of possibilities for your web development projects. Whether you’re logging data, handling complex objects, or calling Blazor methods from JavaScript, these techniques can make your applications more powerful and flexible.

What's your experience with Blazor and JavaScript? Any real-world examples where you need a specific JavaScript library?

Happy coding and have an awesome weekend!

Take care,

Patrick

PS: Need help understanding .NET & Blazor? There are two ways I can help you with:

  1. Check out the .NET Web Academy, which provides masterclasses and a supportive community of like-minded developers.
  2. I'm open to coaching. If you need specific help, reply to this email and we'll figure something out.

PPS: Would you like to sponsor this newsletter? Click here. šŸ’Œ

Patrick God

Become a .NET & Blazor expert with weekly tutorials featuring best practices and the latest improvements, right in your inbox.

Read more from Patrick God

Hey Reader, Last week, I tested GPT-5 Agent Mode on .NET and Blazor apps, and the results were surprising. This week, I went a step further. I used GitHub Copilot inside Visual Studio and asked it to create real .NET and Blazor projects for me. Here’s what happened: Copilot generated a working calculator app in C#. It built a Web API that responded with ā€œHello GPT-5 Agents.ā€ It even created a Blazor app with extra features like a reset button, a plus five counter, and a weather API. Were...

video preview

Hey Reader, I just published a new video where I put GPT-5’s Agent Mode to the test. šŸš€ Instead of asking it for something simple, I went all in: A .NET 9 console app calculator A Web API with endpoints and docs A Blazor Server app with extra counter buttons And even a Blazor app that calls a public weather API šŸŽ„ Watch it now: In the video, I didn’t just type ā€œmake me an appā€ and hope for the best. I gave GPT-5 very specific prompts, like: ā€œPlease create a .NET 9 console application that works...

Hey Reader, I’m back! šŸŽ‰ I’ve been on parental leave for the past 2 months, enjoying time with the family. Now I’m diving back into videos and here’s the first one! šŸŽ„ Watch it now: Here’s the TL;DR if you can’t click right now: AI can already write code, fix bugs, and explain complex concepts. So… are we doomed? No. AI isn’t replacing developers anytime soon. But: Developers who use AI will replace those who don’t. The best devs are using GPT to: Skip repetitive work Prototype faster Learn...