Web-Development-with-Blazor.../Chapter10/MyBlog/Components/Pages/JSInteropSamples/JSToReferenceNET.razor
2023-02-17 15:28:17 +01:00

45 lines
1.1 KiB
Plaintext

@page "/jstoreferencenet"
@implements IDisposable
@inject IJSRuntime JS
<h3>This is a demo how to call .NET from JavaScript using a .NET reference</h3>
@*
This demo shows how to call a JavaScript method with an instance of a .NET object.
The JavaScript then calls a method on the .NET object.
The JavaScript file JSToReferenceNET.js is included in the _layout/index page.
*@
<p>
<label>
Name: <input @bind="name" />
</label>
</p>
<p>
<button @onclick="TriggerDotNetInstanceMethod">
Trigger .NET instance method
</button>
</p>
<p>
@result
</p>
@code {
private string? name;
private string? result;
private DotNetObjectReference<JSToReferenceNET>? dotNetHelper;
public async Task TriggerDotNetInstanceMethod()
{
dotNetHelper = DotNetObjectReference.Create(this);
result = await JS.InvokeAsync<string>("callreferencenetfromjs", dotNetHelper);
}
[JSInvokable]
public string GetHelloMessage() => $"Hello, {name}!";
public void Dispose()
{
dotNetHelper?.Dispose();
}
}