Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor invokeMethodAsync cannot find method

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.

like image 675
Aydin Biber Avatar asked May 23 '26 10:05

Aydin Biber


1 Answers

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.

like image 53
Umair Avatar answered May 24 '26 23:05

Umair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!