简体   繁体   中英

In Blazor, how can I call a JS function from within a static C# method?

In a razor file, I inject @inject IJSRuntime JSRuntime . In the code behind, I invoke a JS function with the following code:

private async Task DownloadPdf(bool foo)
{
    await using var module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./create-pdf.js");
    await module.InvokeVoidAsync("generatePdf", foo);
}

This works well but now I need to call a JS function from C# code that is not code behind but a separate *.cs file:

public static class Bar
{
    public static double Baz()
    {
        // do something
        // call JS function
        return baz;
    }
}

I tried this approach but JSRuntime is always null . How can I invoke JS from my static C# method?

  • Assuming that Baz will always be a static method then you will need to pass in the IJSRuntime object into Bar.Baz .
    • Do not be tempted to pass IJSRuntime via a static field or property on class Bar : this will break your application as static data is shared by all threads.
  • Also, seeming as IJSRuntime.InvokeAsync is a Task -returning async method, you will need to make Bar.Baz similarly also async.

Like so:

public static class Bar
{
    public static async Task<Double> BazAsync( IJSRuntime js, CancellationToken cancellationToken = default )
    {
        if( js is null ) throw new ArgumentNullException(nameof(js));

        // do something

        // call JS function:
        _ = await js.InvokeAsync<TReturnValue>( identifier: "someFunction", cancellationToken, args: new Object[] { "abc", 123 } );


        // return
        Double baz = 123.45d;
        return baz;
    }
}

Then you can call it from your Blazor code-behind class like so:

public partial class MyCodeBehindClass
{
    [Inject]
    IJSRuntime JSRuntime { get; set; }

    private async Task DoSomethingAsync()
    {
        Double baz = await Bar.BazAsync( this.JSRuntime );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM