Skip to content

DotNetInstanceMethod

Mika Berglund edited this page Feb 28, 2024 · 3 revisions

DotNetInstanceMethod Class

This class encapsulates a method on a .NET class instance that can be called from JavaScript code. An instance of this class can be passed as argument when calling a JavaScript function from .NET through interop.

Inheritance

DotNetInstanceMethod : IDisposable

Please note! The DotNetInstanceMethod class implements the IDisposable interface, you need to dispose of the object instance when you are done with it to prevent memory leaks and other unwanted side effects.

Example

This sample shows how to use the DotNetInstanceMethod class in a Blazor component to call a JavaScript function where you pass in a reference to a method in your .NET code that you want the JavaScript code to call back.

This is useful in scenarios where your JavaScript function cannot directly return a value from the function call, but calls a JavaScript callback with the response to the original function call.

There are several such libraries out there. In this sample we use the setTimeout() JavaScript function just to keep the example as simple as possible.

The JavaScript function would look like this.

export function getDelayedTimeString(callback) {
    setTimeout(() => {
        callback.target.invokeMethodAsync(
            callback.methodName,
            new Date().toLocaleTimeString()
        );
    }, 100);
}

To call this function from your C#, you could do like shown below. The code below assumes that you have the following namespaces specified with using statements.

using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.JSInterop;
using Blazorade.Core.Interop;

Then, add the following members to your component.

[Parameter]
public string Data { get; set; }

[Inject]
private IJSRuntime JSRuntime { get; set; }

private DotNetInstanceMethod Callback;
[JSInvokable]
public Task CallbackAsync(string data)
{
    this.Data = data;
    this.Callback.Dispose();
    return Task.CompletedTask;
}

private async Task ButtonClickHandlerAsync(MouseEventArgs args)
{
    var module = await this.GetJsModuleAsync();
    this.Callback = DotNetInstanceMethod.Create(this.CallbackAsync);
    await module.InvokeVoidAsync("getDelayedTimeString", this.Callback);
}

private Task<IJSObjectReference> jsModule;
private Task<IJSObjectReference> GetJsModuleAsync()
{
    return jsModule
        ??= this.JSRuntime
            .InvokeAsync<IJSObjectReference>("import", "./js/your-js-file.js")
            .AsTask();
}

Then, using for instance the <button/> element you can hook the click event to your click handler above, like this.

<button @onclick="this.ButtonClickHandlerAsync">Click to get data</button>
<p>
    Data: @this.Data
</p>

See Also

This class is used by the DotNetInstanceCallbackHandler class, which supports more advanced interop scenarios.

Clone this wiki locally