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.
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 ;-))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With