I ran into a problem that should've taken me no time to solve had I found better examples online.

I refactored some code so I could just call a single static method from my JavaScript rather than replicate that method as a non-static in a handful of Blazor pages that share the same Js file. 

Microsoft shows how to do this with a very simple example:

This works swimmingly... provided the same Blazor page that uses the JavaScript exposes that function directly. If, however, you want to expose a different static method in a different class, you can't just declare it as such. 

I tried different permutations trying to stuff the appropriate namespace everywhere:

  • DotNet.invokeMethodAsync('BlazorSample.MyClass', 'ReturnArrayAsync')
  • DotNet.invokeMethodAsync('BlazorSample', 'MyClass.ReturnArrayAsync')

Then I started to decorate the method itself:

  • [JSInvokable("MyClass.ReturnArrayAsync")]
  • [JSInvokable("BlazorSample.MyClass.ReturnArrayAsync")]

Turns out I was overthinking it. THIS IS WHAT WORKS.

  • [JSInvokable("ReturnArrayAsync")]

So... the JSInvokable attribute can take an optional name parameter that will allow you to expose a static method from your assembly in any class that hosts a static method provided you decorate it properly and invoke it propertly. From the JavaScript side, it's now this:

const test = await DotNet.invokeMethodAsync('BlazorSample', 'ReturnArrayAsync');

A more careful reading of the error messages in the debugger console would've led me here sooner... but it's Friday and half my neurons slipped into weekend mode earlier than I would've liked. 

 

 

Comments


Comments are closed