-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathDotNetInstanceMethodFromJavascript.razor
54 lines (44 loc) · 1.8 KB
/
DotNetInstanceMethodFromJavascript.razor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@using Microsoft.JSInterop
@implements IAsyncDisposable
<button class="[ bg-fuchsia-500 ] [ px-4 py-2 ] [ inline-block ] [ rounded-md ] [ inline-flex ] [ space-x-1 ]" @onclick="() => CallDotNetInstanceFromJs()">
<svg xmlns="http://www.w3.org/2000/svg" class="[ icon icon-tabler icon-tabler-brand-javascript ] [ text-white ]" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
<path d="M20 4l-2 14.5l-6 2l-6 -2l-2 -14.5z"></path>
<path d="M7.5 8h3v8l-2 -1"></path>
<path d="M16.5 8h-2.5a0.5 .5 0 0 0 -.5 .5v3a0.5 .5 0 0 0 .5 .5h1.423a0.5 .5 0 0 1 .495 .57l-.418 2.93l-2 .5"></path>
</svg>
<span class="[ text-white ]">Calling .Net instance Method from JS</span>
</button>
@code {
private DotNetObjectReference<DotNetInstanceMethodFromJavascript>? objRef;
private IJSObjectReference? module;
[Inject] private IJSRuntime JSRuntime { get; set; } = default!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./jsinterop.js");
}
}
private async Task CallDotNetInstanceFromJs()
{
if (module is not null)
{
objRef = DotNetObjectReference.Create(this);
await module.InvokeVoidAsync("callDotNetInstanceFromJs", objRef);
}
}
[JSInvokable]
public string GetMessageFromDotNet()
{
return "DotNet ❤️ JS";
}
async ValueTask IAsyncDisposable.DisposeAsync()
{
objRef?.Dispose();
if (module is not null)
{
await module.DisposeAsync();
}
}
}