Calling JS from .Net code no longer works after updating Visual Studio

67 Views Asked by At

The following was working just fine under VS 2022 v17.7.6 (and still is on another PC). However under VS 2022 v17.8.2 I get an error.

In .cs code behind:

[Inject] IJSRuntime? JSRT { get; set; }
DotNetObjectReference<GraphicalUngrouped>? objectReference;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender) await BundleAndSendDotNetHelper();
}

private async Task BundleAndSendDotNetHelper()
{
    objectReference = DotNetObjectReference.Create(this);
    if (JSRT != null)
    {
        await JSRT.InvokeAsync<string>("SetDotNetHelper", objectReference);
    }
}

In the .razor page

<script>
    function SetDotNetHelper(dotNetHelper) {
        window.dotNetHelper = dotNetHelper;
    }
</script>

This was working. Now I get the following error:

 Unhandled exception rendering component: Could not find 'SetDotNetHelper' ('SetDotNetHelper' was undefined).
  Error: Could not find 'SetDotNetHelper' ('SetDotNetHelper' was undefined).
      at https://localhost:7211/_framework/blazor.webassembly.js:1:328
      at Array.forEach (<anonymous>)...

Not sure if it makes any difference but the code is in a component on a page.

Can anyone offer any insights, or suggestions please?

Oh, this is .Net Core 6 in case that's relevant.

1

There are 1 best solutions below

3
Ruikai Feng On

Please check this document related:

Don't place a tag in a Razor component file (.razor) because the tag can't be updated dynamically by Blazor.

Try to move your js codes from razor component to _Layout.cshtml in the <body> markup and check if it would work now