Paul
Paul

Reputation: 1006

Blazor (client/wasm) JSInvoke "Value cannot be null" error

I'm tring to run a javascript function called loadJsOrCssFile which takes 2 string parameters using the code below :

await JSRuntime.InvokeAsync<string>("loadJsOrCssFile", $"/brands/{_brand.BrandId}/brand{_brand.BrandId}_{_brand.CSSFileVersionNo}.css", "css");

But I get an error (from Chrome dev tools console) :

blazor.webassembly.js:1 WASM: System.ArgumentNullException: Value cannot be null.
h.printErr @ blazor.webassembly.js:1
12:37:36.127 blazor.webassembly.js:1 WASM: Parameter name: jsRuntime
h.printErr @ blazor.webassembly.js:1
12:37:36.127 blazor.webassembly.js:1 WASM:   at Microsoft.JSInterop.JSRuntimeExtensions.InvokeAsync[TValue] (Microsoft.JSInterop.IJSRuntime jsRuntime, System.String identifier, System.Object[] args) <0x281f210 + 0x00014> in <3eedf0ca90ca4e72bf6870618ca98c7c>:0 

Upvotes: 2

Views: 5245

Answers (2)

Porkopek
Porkopek

Reputation: 1012

For other users that came here from google, you have to inject it in the traditional way

    public class MyClass
    {
        private readonly IJSRuntime _jSRuntime;

        public MyClass (IJSRuntime jSRuntime)
        {
            _jSRuntime = jSRuntime;
        }
     }

Upvotes: 2

Paul
Paul

Reputation: 1006

Sorry, this doesn't matter now I have worked it out. I was doing this at the top of the class (this is a normal class and not within a component) :

[Inject]
IJSRuntime JSRuntime { get; set; }

It works if I get the JSRuntime through DI within the constructor.

Upvotes: 3

Related Questions