Easier JavaScript Interoperability in Blazor with Anonymous Types

Often in JavaScript, you’ll come across a function that requires or supports an options object as an argument.

A good example of this is the SweetAlert library, which you typically call or invoke like so to prompt the user with a beautiful interactive alert on your page:

    title: "Good job!",
    text: "You clicked the button!",
    icon: "success",

Notice how we create and pass a new object with all of the options that the function needs to do its job as its primary argument.

This is usually cleaner and easier than sending a list of unmemorable arguments in the correct order.

In Blazor, however, when we perform calls to our JavaScript functions or those of packages that we’ve included, the default way to invoke functions is through a simple list of arguments:

JSRuntime.InvokeVoidAsync("alert", "This is an alert!");

In this example, we are calling the web browser’s alert function to prompt the user with a message through Blazor’s IJSRuntime abstraction for interoperating between C# and JavaScript.

It works, but it’s not a very sophisticated alert.

What if we wanted to use the nicer SweetAlert library instead?

This is where I’ve found that we can leverage a useful feature of the C# language to do it as effortlessly as we do in JavaScript: Anonymous Types.

Once we’ve included the SweetAlert library in our web application — either by a simple <script> tag in our _Host.cshtml file, by importing it in our JavaScript bundle, or any other method — we can invoke it from our Blazor component:

await JSRuntime.InvokeAsync<bool>("swal", new {
    title = "Good job!",
    text = "You clicked the button!",
    icon = "success"

With an anonymous type, we don’t have to bother with creating a new class for a single JavaScript function argument and then handling that new type in our interoperability layer.

The anonymous type is serialized to JSON and then parsed as an object argument to the JavaScript function being invoked in the browser.

We can simply declare a new object almost as easily as we can do it in JavaScript!

One thought on “Easier JavaScript Interoperability in Blazor with Anonymous Types

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s