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?
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");
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With