Q:

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

0

This code will help you to understand how to call a JavaScript function from .NET using JavaScript Interop.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In Blazor, IJSRuntime interface is used to invoke a JavaScript function from .NET.

Using the InvokeAsync<T> method of IJSRuntime abstraction, we can call the JavaScript function. This method takes the function name and function parameters as the argument.

Task<T> InvokeAsync<T>(string identifier, params object[] args);

The JavaScript function should always be written in the index.html file. Open the wwwroot/index.html file and put in the following code.

<html>
<head></head>
<body>
    <app>Loading...</app>

    <script src="_framework/blazor.webassembly.js"></script>
    <script>
        function JSMethod() {
            document.getElementById('demop').innerText = "Javascript Method Invoked";
        }
</body>
</html>

Open JSInterop.cshtmland put in the following code.

@page "/jsinterop"
@inject IJSRuntime JsRuntime;

<h1>JavaScript Interop</h1>

<hr />

<button class="btn btn-primary" @onclick="@CallJSMethod">Call JS Method</button>

<br />
<div id="demop"></div>

@code {
    Protected async void CallJSMethod()
    {
        await JSRuntime.InvokeAsync<string>("JSMethod");
    }
}

The method CallJSMethod will call JS function JSMethod by using the JSRuntime.InvokeAsync method.

Important notes

  • Do not write your JS code in the .cshtml file. This is not allowed in Blazor and the compiler will throw an error. Always put your JS code in the wwwroot/index.html file.
  • Always add your custom <script> tag after “<script src=”_framework/blazor.webassembly.js”> </script>” in the <body> section of the index.html file. This is to ensure that your custom script will execute after loading the “blazor.webassembly.js” script.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now