How To call a C# method from JavaScript

As per the Wikipedia

Blazor is a free, open-source web framework that enables developers to create web apps using C# and HTML. Microsoft is developing it.

This blog post will show you how to call the C# static method from JavaScript in Blazor. It is straightforward to call the C# static method from JavaScript. To invoke, follow the following steps.

  • Create a static method
  • Add attribute [JSInvokable] so that blazor is aware of the method
  • Create a JavaScript function and invoke the method below

DotNet.invokeMethodAsync(["ASSEMBLYNAME"],
["C# STATIC METHOD NAME"],["ARGS"])

Let’s understand this with an example. Create a Blazor Page named CallDotNetMethodFromJavaScript and add the following code. The code is self-explanatory. I have added a button with a click event and one static method with the attribute JsInvokable.

@page "/dotnet"
 <button onclick="callDotNetMethod()">
        Trigger .NET static method
    </button>

@code{
    [JSInvokable]
    public static async Task<string> DotnetMethod(string name){
            await Task.Delay(100);
            return $"Hello {name}";

    }
}

Now go to your Index.html or _Layout.cshtml file and call the dotnet function as shown below.

	 <script>
        window.callDotNetMethod = () => {
          DotNet.invokeMethodAsync('dotnetguru-blog', 'DotnetMethod',"Dotnet Guru")
            .then(data => {
             alert(data);
            });
          };
      </script> 

Things to remember

  • You can not create an overloaded static method with the JsInvokable attribute. If you do so, you will get the following error.
System.InvalidOperationException: The assembly 'AssemblyName' contains more than one [JSInvokable] method with identifier 'DotnetMethod'. All [JSInvokable] methods within the same assembly must have different identifiers. You can pass a custom identifier as a parameter to the [JSInvokable] attribute.
  • If you want to create an overloaded method, then pass the identifier name to the JSInvokable constructor as shown below
 [JSInvokable("DotnetMethodWithArgument")]
    public static async Task<string> DotnetMethod(string name){
            await Task.Delay(100);
            return $"Hello {name}";

    }
    [JSInvokable("DotnetMethod")]
     public static async Task<string> DotnetMethod(){
            await Task.Delay(100);
            return $"Hello ";

    }

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru