The assembly does not contain a public invokable method with [JSInvokableAttribute]

Viewed 3558

We use Blazor WebAssembly and I want to call an non-static method in my Index.razor-File by JavaScript.

JavaScript:

(function () {

    // keydown event
    window.addEventListener("keydown", function (e) {
        DotNet.invokeMethodAsync('MyBlazorWebAssemblyApp.Client', 'MyMethod');
    });
})();

Index.razor:

@page "/"
@inject HttpClient Http

@code {
    
    // [...]
    
    [JSInvokable]
    public async Task MyMethod()
    {
        var lResponse = await Http.GetFromJsonAsync<object>("Controller/Action");
    }
}

When I execute the code by an keydown, then the developer tools in Microsoft Edge shows me the following error:

blazor.webassembly.js:1 System.ArgumentException: The assembly 'MyBlazorWebAssemblyApp.Client' does not contain a public invokable method with [JSInvokableAttribute("MyMethod")].

When I replace the attribute [JSInvokable] by [JSInvokableAttribute("MyMethod")] then the same error appears.

How can I fix this problem?

2 Answers

Got it working now by my self. Here is the code:

JavaScript:

var GLOBAL = {};
GLOBAL.DotNetReference = null;
GLOBAL.SetDotnetReference = function (pDotNetReference) {
    GLOBAL.DotNetReference = pDotNetReference;
};

(function () {

    // keydown event
    window.addEventListener("keydown", function (e) {
        GLOBAL.DotNetReference.invokeMethodAsync('MyMethod');
    });
})();

Index.razor:

@page "/"
@inject HttpClient Http

@code {
    
    protected override async Task OnInitializedAsync()
    {
        var lDotNetReference = DotNetObjectReference.Create(this);
        JSRuntime.InvokeVoidAsync("GLOBAL.SetDotnetReference", lDotNetReference);
    }
    
    // [...]
    
    [JSInvokable("MyMethod")]
    public async Task MyMethod()
    {
        var lResponse = await Http.GetFromJsonAsync<object>("Controller/Action");
    }
}
Related