How do you call a .NET function from JavaScript using JavaScript Interop?

There are two methods to call a method from JavaScript:

  • DotNet.invokeMethod
  • DotNet.invokeMethodAsync

The syntax of calling a C# method from JavaScript is as follows.

DotNet.invokeMethodAsync('C# method assembly name', 'C# Method Name');

Add the .NET function invoke statement to a script in the head of Pages/_Host.cshtml file.

<script>
   function CSMethod() {
      DotNet.invokeMethodAsync('BlazorTestApp', 'CSCallBackMethod');
   }
</script>

Here we are defining a JavaScript function “CSMethod”. This function will have a callback to our .NET function “CSCallBackMethod” which is defined in index.razor.

To invoke C# method from JavaScript,

  • The method must be decorated with “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.
@page "/jsinterop"
@inject IJSRuntime JsRuntime;

<button @onclick="WriteToConsole">Call .NET Method</button>
<br />
<p>@message</p>


@code {
    protected static string message { get; set; }

    [JSInvokable]
    public static void CSCallBackMethod()
    {
        message = "C# Method invoked";
    }

    private async Task WriteToConsole()
    {
        await JsRuntime.InvokeAsync<object>("CSMethod");
    }
}

Reference LinkReference link

https://www.freecodecamp.org/news/how-to-implement-javascript-interop-in-blazor-9f91d263ec51/

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.