skip to content

When a JavaScript map in a Blazor component must call back into .NET on a marker click, how do DotNetObjectReference and [JSInvokable] work?

level: middleimportance: should knowfreq 48%

answer

  1. DotNetObjectReference.Create(this)
  2. [JSInvokable] on a public method
  3. dotNetHelper.invokeMethodAsync('OnTrailSelected', id)
  4. static: DotNet.invokeMethodAsync(assembly, id)
  5. dispose it, then StateHasChanged after callbacks

basics

~10 s

Wrap the component with DotNetObjectReference.Create(this), pass it to JavaScript, and mark the target public method [JSInvokable]. JavaScript calls dotNetHelper.invokeMethodAsync('OnTrailSelected', id); dispose the reference when the component goes away.

solid answer

~40 s

`DotNetObjectReference.Create(this)` registers the component instance with the JS interop layer and returns a reference that serializes as a callable proxy. Passed as an argument, JavaScript receives an object with `invokeMethodAsync(methodIdentifier, ...args)`; the target must be a **public** method marked `[JSInvokable]`, optionally with an explicit identifier. Static methods need no instance: `DotNet.invokeMethodAsync('AssemblyName', 'MethodId', ...)`. The reference keeps the component reachable from the interop registry, so dispose it in `Dispose` or `DisposeAsync`; calls through a disposed reference fail. A callback from JavaScript is not an `EventCallback`, so call `StateHasChanged()` after changing state the UI shows. Treat the arguments as untrusted input, because any script in the page can call the method.

code

razor · 26 lines
razor
@implements IDisposable
@inject IJSRuntime JS
<div @ref="mapElement" class="trail-map"></div>
<p>@selected?.Name</p>
@code {
    [Parameter, EditorRequired] public IReadOnlyList<Trail> Trails { get; set; } = default!;
    private ElementReference mapElement;
    private DotNetObjectReference<TrailMap>? selfRef;
    private Trail? selected;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender) return;
        selfRef = DotNetObjectReference.Create(this);
        await JS.InvokeVoidAsync("trailMap.init", mapElement, Trails, selfRef);
    }

    [JSInvokable]
    public void OnTrailSelected(int trailId)
    {
        selected = Trails.FirstOrDefault(t => t.Id == trailId);  // untrusted input: look it up
        StateHasChanged();
    }

    public void Dispose() => selfRef?.Dispose();
}

go deeper

for a junior

Recall DotNetObjectReference.Create(this), the [JSInvokable] attribute and invokeMethodAsync on the JavaScript side.

for a middle

Explain instance versus static calls, the public-method requirement, why StateHasChanged is needed and why the reference must be disposed.

for a senior

Prevent leaks and stale callbacks, validate callback arguments, and throttle chatty JavaScript events on Interactive Server.

for a principal

Define which component APIs are reachable from JavaScript at all, since every [JSInvokable] method is a callable surface for any script on the page.

## The two directions In Blazor JavaScript interop, `IJSRuntime` covers .NET calling JavaScript. The reverse direction, JavaScript calling .NET, has two forms: | Form | .NET side | JavaScript side | |---|---|---| | Static method | `[JSInvokable] public static` method | `DotNet.invokeMethodAsync('{ASSEMBLY NAME}', 'MethodId', ...args)` | | Instance method | `[JSInvokable] public` instance method, plus a `DotNetObjectReference` | `dotNetHelper.invokeMethodAsync('MethodId', ...args)` | A map marker click needs to reach **this** component instance, so the instance form is the usual answer. ## How the instance form works 1. **Create the reference.** `DotNetObjectReference.Create(this)` returns a `DotNetObjectReference<TrailMap>`. The interop layer gives it an id and keeps the instance in a tracking table. 2. **Pass it to JavaScript.** As an argument to `InvokeVoidAsync`, it serializes as that id; JavaScript receives an object exposing `invokeMethodAsync` (and, client-side only, the synchronous `invokeMethod`). 3. **Mark the target.** The .NET method must be **public** and carry `[JSInvokable]`. By default its identifier is the method name; `[JSInvokable("trailSelected")]` sets another. 4. **Call back.** `dotNetHelper.invokeMethodAsync('OnTrailSelected', trailId)` returns a JavaScript `Promise` resolved with the method's serialized return value; arguments are deserialized with the same JSON rules as the other direction. ## Rendering after a callback A `[JSInvokable]` method is invoked by the interop dispatcher, not by Blazor's event system. Unlike an `@onclick` handler, nothing automatically re-renders the component afterwards. When the callback changes state the UI shows, such as the selected trail's details panel, call `StateHasChanged()` at the end of it. ## Disposal and leaks The tracking table holds a strong reference to the instance. If the component is removed without disposing its `DotNetObjectReference`, the component and everything it references stay alive for the life of the circuit or the WebAssembly app. - Dispose it from .NET in the component's `Dispose`/`DisposeAsync`, or from JavaScript with `dotNetHelper.dispose()` when the JavaScript side is done with it. - After disposal, a JavaScript call through the stale proxy fails; the .NET side reports that there is no tracked object with that id and suggests the reference was already disposed. - Have the JavaScript teardown remove the map's listeners first, so a late click does not call into a disposed reference. ## Security and robustness - Any script running in the page can call a `[JSInvokable]` method with any arguments. Validate them as untrusted input, for example check that the trail id belongs to the current user, before acting. - Keep callback payloads small; on Interactive Server each call is a message over the circuit. - For high-frequency events such as map panning, throttle in JavaScript and send only the final viewport, rather than calling .NET on every mouse move. ## Asynchronous callbacks and return values A `[JSInvokable]` method may return a value or a `Task`/`Task<T>`: - A returned value is serialized to JSON and resolves the JavaScript promise from `invokeMethodAsync`. - A `Task` is awaited first, so JavaScript can `await dotNetHelper.invokeMethodAsync('LoadTrailDetailsAsync', id)` and receive the data a .NET service fetched. - An exception thrown by the .NET method rejects the promise; handle it in JavaScript rather than letting a click handler fail silently. - If the method awaits work and then updates the UI, call `StateHasChanged()` after the awaited work completes, not before it. ## Common mistakes - Creating a new `DotNetObjectReference` on every render instead of once behind `firstRender`, leaking one per render. - Passing `this` directly instead of a `DotNetObjectReference`: the serializer then tries to copy the component's public properties as JSON data, which is not a callable reference and may not serialize at all. - Forgetting that the JavaScript name is the method name, or the identifier given to `[JSInvokable(...)]`, and renaming one side only. - Expecting an instance call to work with `DotNet.invokeMethodAsync`, which is only for static methods. ## Static methods A static `[JSInvokable]` method suits callbacks that need no component instance, such as a utility that formats a distance. The assembly name is part of the call (`DotNet.invokeMethodAsync('HikingTrails', 'FormatDistance', meters)`), and identifiers must be unique within that assembly.

  • A [JSInvokable] method is declared private and JavaScript's invokeMethodAsync rejects; why?
    The interop dispatcher looks up only public methods carrying `[JSInvokable]`, for instance methods on the referenced type and static methods in the named assembly. A private method is never registered, so the call fails. Make it public; if exposing it on the component bothers you, move it to a small helper class and reference that instead.
  • Memory on an Interactive Server app grows each time users open and leave the trail page; what is a likely interop cause?
    A `DotNetObjectReference` created in `OnAfterRenderAsync` but never disposed. The interop layer keeps a strong reference to the component, so every visit leaves one alive until the circuit ends. Dispose it in the component's `Dispose`/`DisposeAsync`, or from JavaScript with `dispose()`, and remove the JavaScript listeners that use it.

  • Any public method of the component can be called from JavaScript without an attribute.
  • DotNetObjectReference is released by the garbage collector, so disposal is optional.
  • A [JSInvokable] callback re-renders the component automatically like @onclick.
  • JSInvokable arguments come from Blazor, so they need no validation.
  • Static .NET methods also need a DotNetObjectReference to be called from JavaScript.