Reputation: 545
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?
Upvotes: 1
Views: 1902
Reputation: 155165
Baz
will always be a static
method then you will need to pass in the IJSRuntime
object into Bar.Baz
.
IJSRuntime
via a static
field or property on class Bar
: this will break your application as static
data is shared by all threads.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 );
}
}
Upvotes: 5