Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 416
Simon Avatar asked Jul 17 '20 12:07

Simon


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");
    }
}
like image 131
Simon Avatar answered Oct 22 '22 00:10

Simon


If you check out the Microsoft documentation at the following link:

https://learn.microsoft.com/en-gb/aspnet/core/blazor/call-dotnet-from-javascript?view=aspnetcore-3.1#instance-method-call

This differs from your example in the following ways:

Your JavaScript appears to be trying to call a static .NET method.

Your C# code is not a static method.

like image 1
Mark3308 Avatar answered Oct 21 '22 22:10

Mark3308