Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Blazor method From JavaScript

I'm experimenting with Blazor in Visual Studio, specifically with calling Blazor code from JavaScript. I'm reasonably confident that I've got all the right libraries in place. However, when I attempt to call my Blazor method with invokeMethodAsync, I get the message "no .net call dispatcher has been set". In my Index.Html file, I have this:

<script> DotNet.invokeMethodAsync("BlazorFour.App", "HelloYou").then(data => alert(data), reason => alert(reason)); </script>

(It's the alert(reason) that generates the error message)

I've added a class file to my Blazor project and it contains this:

using Microsoft.JSInterop;
using System.Threading.Tasks;
public class HelloWorld
{
[JSInvokable]
public static Task<string> HelloYou()
{
    return Task.FromResult("Hello, ");
}
}

I've used all the templates in Visual Studio and the dotnet -new blazor commandline utility to create my start points but get the same message in all of the projects. It's seems likely to me that I'm missing something fundamental here.

like image 658
Peter Vogel Avatar asked Aug 06 '18 15:08

Peter Vogel


1 Answers

I'm using server-side-blazor

I was getting js errors No .NET call dispatcher has been set

So yep .. looks like Blazor wasn't initialized..

Not keen on a timeout .. seems hacky and gives a laggy UI

Not keen on 'call JavaScript code from your C# code. Once you've done that, your JavaScript code can, in turn, call Blazor code.' .. again seems hacky

This works for me ..

async function myBlazoryFunctionThing() {
    // see https://sourcegraph.com/github.com/aspnet/AspNetCore@bd65275148abc9b07a3b59797a88d485341152bf/-/blob/src/Components/Web.JS/src/Boot.Server.ts#L41:9
   await window.Blazor.reconnect();
   
   ..now it's safe to do my stuff
}

it 'seems' that Blazor.reconnect() will re-use the existing connection (if there is one)

...so it's not actually 're-connecting' (so 'seems' not much overhead ;-))

like image 118
stooboo Avatar answered Oct 05 '22 11:10

stooboo