Inside a Blazor component, I want to call a JS method from the HTML onclick event of an anchor tag, thus:
<a onclick="window.LoadImage();" class="@CssClass">@DisplayName</a>
My JS method is:
window.LoadImage = () => {
DotNet.invokeMethodAsync('MyProject', 'FireEvent').then();
}
Inside the JS method, I want to fire a C# static method to trigger an event, thus:
[JSInvokable]
public static void FireEvent()
{
StateEngine.LoadImage(DisplayName, Target);
}
[Parameter]
public string DisplayName { get; set; }
[Parameter]
public string Target { get; set; }
I can't get the JS method to find the C# method. I've tried multiple name configurations for the first parameter, like
MyProject (the assembly name)
MyProject.FolderName.ComponentName
FolderName.ComponentName
ComponentName
to name a few. I've also tried shuffling names through the second parameter.
How is this supposed to work? What am I missing?
P.S. Please disregard the bit about the instance properties in the static method. I've got a workaround for that, but don't want to clutter up the post.
From the looks of it, you would be better off using the reference JSInterop so you can access the components properties.
Razor
@inject IJSRuntime JS
@implements IDisposable
<a @onclick=Clicked>Click here</a>
@code
{
private DotNetObjecctReference ObjRef;
[JSInvokable]
public void FireEvent()
{
StateEngine.LoadImage(DisplayName, Target);
}
private Task Clicked()
{
return JS.InvokeVoidAsync("window.LoadImage", ObjRef);
}
protected override Task OnInitializedAsync()
{
ObjRef = DotNetObjectReference.Create(this);
}
void IDisposable.Dispose()
{
ObjRef.Dispose();
}
}
JS
window.LoadImage = (dotNetObject) => {
dotNetObject.invokeMethod('FireEvent');
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments