I'm calling a C# method from Javascript using invokeMethodAsync. I had it working a day ago but it has broken since and no amount of reverting my changes seems to fix it.
Error: System.ArgumentException: The assembly 'HelloWorld' does not contain a public invokable method with [JSInvokableAttribute("GetCodeFromList")].
The JS:
DotNet.invokeMethodAsync('HelloWorld', 'GetCodeFromList')
.then(data => {
data.push(result.codeResult.code);
}
);
The result.codeResult.code is the number I want to receive on the C# side. I have already confirmed that the number is correct.
The C#:
[JSInvokable]
public void GetCodeFromList(long jsCode)
{
code = codes.Where(p => p.SecretCode.Equals(jsCode)).FirstOrDefault();
StateHasChanged();
}
I have another .razor file where I have a method also called GetCodeFromList that I also want to be accessible using the same invoke, but I have tried completely removing it and that didn't solve the problem.
You will have to change your C# method to static:
Updated answer: You will have to pass the reference of the class instance to your javascript method which will use that to call your method.
public async Task TriggerDotNetInstanceMethod()
{
objRef = DotNetObjectReference.Create(this); <--- this is the instance reference you have to pass
result = await JS.InvokeAsync<string>("sayHello1", objRef);
}
[JSInvokable]
public void GetCodeFromList(long jsCode)
{
code = codes.Where(p => p.SecretCode.Equals(jsCode)).FirstOrDefault();
StateHasChanged();
}
And javascript:
<script>
window.sayHello2 = (dotNetHelper, name) => {
return dotNetHelper.invokeMethodAsync('GetCodeFromList', name);
};
</script>
Check here and here for more info.
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