JavaScript to .NET
What about the other way around? I would argue that calling .NET code from JavaScript isn’t a very common scenario, and if we find ourselves in that scenario, we might want to think about what we are doing.
I think that as Blazor developers, we should avoid using JavaScript as far as possible. There are, of course, times where JavaScript is the only option, and as I mentioned earlier, Blazm uses communication both ways.
There are three ways of doing a callback from JavaScript to .NET code:
- Static .NET method call
- Instance method call
- Component instance method call
Let's take a closer look at them.
Static .NET method call
To call a .NET function from JavaScript, we can make the function static and we also need to add the JSInvokable
attribute to the method.
We can add a function such as this in the code
section of a Razor component, or inside a class:
[JSInvokable] public static Task<int[]> ReturnArrayAsync...