How do I call a C# method from JavaScript in Blazor WebAssembly?

Platform: Blazor|Category: JavaScript Interop

A Blazor app can invoke JavaScript functions from .NET methods and .NET methods from JavaScript functions. These scenarios are called JS interop.

There are two methods to call a C# method from JavaScript.

  1. DotNet.invokeMethod
  2. DotNet.invokeMethodAsync

Syntax to call C# from JavaScript:

DotNet.invokeMethodAsync(“C# method assembly name”, “C# method name”);

To call a C# method from JavaScript,

  • The method must be decorated with the “JSInvokable” attribute.
  • The method must be public.
  • The method may either be static or instance-level (this is only supported by Blazor 0.5.0 and above).
  • The identifier for the method must be unique.
  • The method must be nongeneric.

[Index.razor]

@page "/"

@inject IJSRuntime JsRuntime;

<button class="btn btn-primary" @onclick="OnButtonClick">Call C# from JS</button><br /><br />

<p>@content</p>

@code {
    private static string content { get; set; }

    // Return call back from JavaScript to C#
    [JSInvokable]
    public static void JStoCSCall()
    {
        content = "C# Method called from JavaScript";
    }

    // Invoked by button clicking and calls JavaScript function.
    private async Task OnButtonClick()
    {
        await JsRuntime.InvokeAsync<object>("CStoJSCall");
    }
}

Add the C# function invoke statement to a script tag in the body of the wwwroot/index.html file.

[index.html]

<body>
      . . .
      . . .

   <script>
        function CStoJSCall() {
            // Invoke to call C# function from JavaScript.
            DotNet.invokeMethodAsync('BlazorWasmApp', 'JStoCSCall');
        }
    </script>
</body >

Refer to “Call .NET methods from JavaScript functions in ASP.NET Core Blazor” for more details.