I want to trigger a JavaScript function from .net class in a Blazor Wasm project. I created a class (client side)
public class InvokeMyJavaScript
{
private readonly IJSRuntime jSRuntime;
public InvokeMyJavaScript(IJSRuntime jSRuntime)
{
this.jSRuntime = jSRuntime;
}
public async ValueTask InvokeMyJs()
{
await jSRuntime.InvokeVoidAsync("giveMeAMessage");
}
}
I added to Program.cs:
builder.Services.AddTransient<InvokeJavaScript>();
In my Razor component I now can do this:
[Inject]
InvokeMyJavaScript imjs { get; set; }
public async void InvokeMyJs()
{
await imjs.InvokeMyJs();
}
Works perfectly, thanks to the people who helped me here. but when I try to do this from a class it goes wrong. I tried:
[Inject]
InvokeMyJavaScript ij { get; set; }
private async Task TestnaarJs()
{
await ij.InvokeMyJs();
}
But then I receive an error: Object reference not set to an instance of an object. I cant figure out what is going wrong... How can I inject in a class?
[Inject]attribute will work for component. In order to inject into a normal class then use constructor injection. Read more about that here