简体   繁体   中英

Blazor JS interop - calling C# instance methods from javascript

Two DIFFERENT Blazor components define the following instance method:

[JSInvokable]
public void MyInstanceMethod()
{
...
}

At load time they call a js function, passing themselves to js:

await JS.InvokeAsync<object>("jsFunction", new DotNetObjectRef(this));

In js, the passed .NET object reference is saved in a variable named _callback. Later, an event occurring in javascript calls back the instance method

_callback.invokeMethodAsync("MyInstanceMethod");

The browser console fails with the following error:

blazor.webassembly.js:1 Uncaught (in promise) Error: 
System.InvalidOperationException: 
The assembly 'WebApplication7.Client' contains more than one [JSInvokable] method 
with identifier 'MyInstanceMethod'.
All [JSInvokable] methods within the same assembly must have different identifiers.

BTW, everything goes well if only one component has the method.

Isn't this a violation of one of the fundamental scope features in any OO language?

Can anybody tell me why methods, including instance methods, are required to have different identifiers to be JSInvokable?

If this is a limit of Blazor, is there a plan to fix it?

Looks like there is a bug in Blazor. Steve Sanderson :


Sounds like a bug. Thanks for reporting it.

It makes sense to require static methods to have assembly-wide unique identifiers. However it doesn't make sense that instance methods need assembly-wide unique identifiers. We should only require the identifier to be unique within the type of the instance you're passing.

As a workaround, you could do something like:

[JSInvokable("SomeUniqueIdentifier")]
public void MyInstanceMethod()
{
...
}

I know it's annoying to need a workaround like this. We'll fix the underlying bug (most likely after 3.0 ships).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM