interop_如何在Blazor中实现JavaScript Interop

interop

介绍 (Introduction)

In this article, we will learn about JavaScript Interop in Blazor. We will understand what JavaScript Interop is and how we can implement it in Blazor with the help of a sample application.

在本文中,我们将学习Blazor中JavaScript Interop。 我们将了解JavaScript Interop是什么以及如何在示例应用程序的帮助下在Blazor中实现它。

We will be using Visual Studio code for our demo.

我们将在演示中使用Visual Studio代码。

什么是JavaScript Interop? (What is JavaScript Interop?)

Blazor uses JavaScript to bootstrap the .NET runtime. It is able to use any JS library. C# code can call a JS function/API and JS code can call any C# methods. This property of calling a JS method from C# code and vice versa is referred as JavaScript Interop. Blazor uses JavaScript Interop to handle DOM manipulation and browser API calls.

Blazor使用JavaScript引导.NET运行时。 它可以使用任何JS库。 C#代码可以调用JS函数/ API,而JS代码可以调用任何C#方法。 从C#代码调用JS方法(反之亦然)的属性称为JavaScript Interop。 Blazor使用JavaScript Interop来处理DOM操作和浏览器API调用。

JavaScript Interop is the feature provided by WebAssembly, since Blazor runs on Mono and mono is compiled to WebAssembly. Hence, Blazor can also implement this feature.

JavaScript Interop是WebAssembly提供的功能,因为Blazor在Mono上运行,并且mono被编译为WebAssembly。 因此,Blazor也可以实现此功能。

先决条件 (Prerequisites)

  • Install the .NET Core 2.1 or above SDK from here.

    此处安装.NET Core 2.1或更高版本的SDK。

  • Install visual Studio Code from here.

    此处安装visual Studio代码。

源代码 (Source Code)

Get the source code from Github.

Github获取源代码。

创建Blazor应用程序 (Creating the Blazor application)

We will create a Blazor application using Windows PowerShell.

我们将使用Windows PowerShell创建Blazor应用程序。

第1步 (Step 1)

First, we will install the Blazor framework templates in our machine.

首先,我们将在计算机中安装Blazor框架模板。

Open the folder where you want to create your project. Open Windows PowerShell with shift + right click >> Open PowerShell window Here.

打开要在其中创建项目的文件夹。 使用shift +打开Windows PowerShell,右键单击>>在此处打开PowerShell窗口。

Type in the following command:

输入以下命令:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates

Refer to the image below:

请参考下图:

第2步 (Step 2)

Type in the following command to create our Blazor application:

输入以下命令以创建我们的Blazor应用程序:

dotnet new blazor -o BlazorJSDemo

This will create a Blazor application with the name BlazorJSDemo. Refer to the image below.

这将创建一个名为BlazorJSDemo的Blazor应用程序。 请参考下图。

将剃刀页面添加到我们的应用程序 (Adding the Razor Page to our application)

Open the BlazorJSDemo app using VS code. You can observe the folder structure in Solution Explorer, as shown in the below image.

使用VS代码打开BlazorJSDemo应用程序。 您可以在解决方案资源管理器中观察文件夹结构,如下图所示。

We will add our Razor page in the Pages folder.

我们将在页面文件夹中添加我们的Razor页面。

Create a new file by right clicking on the Pages folder and select New File. Name the file JSDemo.cshtml. This file will contain HTML code to handle the UI of our application.

通过右键单击Pages文件夹并选择New File创建一个新文件。 将文件命名为JSDemo.cshtml 。 该文件将包含HTML代码来处理我们应用程序的UI。

Similarly, add one more file JSDemo.cshtml.cs. This file will contain the C# code to handle our business logic.

同样,再添加一个文件JSDemo.cshtml.cs 。 该文件将包含处理我们的业务逻辑的C#代码。

Now our Pages folder will have the following structure:

现在,我们的Pages文件夹将具有以下结构:

从C调用JavaScript函数 (Calling a JavaScript function from C)

First, we will write our JavaScript functions in index.html file. Open the wwwroot/index.html file and put in the following code:

首先,我们将JavaScript函数写入index.html文件 。 打开wwwroot / index.html文件,并输入以下代码:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
    <title>BlazorJSDemo</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/site.css" rel="stylesheet" />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>

<body>
    <app>Loading...</app>

    <script src="_framework/blazor.webassembly.js"></script>

    <script>
        function JSMethod() {
            $("#demop").text("JavaScript Method invoked");
        }
    </script>

</body>

</html>

Here we have included the CDN reference to JQuery library inside <head> section so that we can handle the DOM manipulation.

在这里,我们在<head>部分中包括了对JQuery库的CDN参考,以便我们可以处理DOM操作。

Inside the <body> section, we have defined our JS function. The function name is JSMethod and it is not accepting any arguments. When triggered it will set the text of a <p> tag having id “demop” to “JavaScript Method invoked”.

在<body>部分中,我们定义了JS函数。 该函数本身就是JS方法,它不接受任何参数。 触发后,会将ID为“ demop”的<p>标记的文本设置为“ JavaScript方法已调用”。

Important Note

重要的提示

  1. 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.

    不要在.cshtml文件中编写JS代码。 Blazor不允许这样做,并且编译器将引发错误。 始终将您的JS代码放在wwwroot / index.html文件中。

  2. Always add your custom <script> tag after “ <script src=”_framework/blazor.webassembly.js”></script>” in the <body&gt; section of index.html file. This is to ensure that your custom script will execute after loading the “ blazor.webassembly.js” script.

    始终在<body&g t;中的“ <script src =” _ framework / blazor.webassembly.js”> </ script>”之后添加自定义<script>标记。 index.html文件的部分。 这是为了确保您的自定义脚本将在加载“ blazor.webassembly.js”脚本后执行。

Open JSDemo.cshtml.cs and put in the following code:

打开JSDemo.cshtml.cs 并输入以下代码:

using Microsoft.AspNetCore.Blazor.Components;
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlazorJSDemo.Pages
{
    public class JSDemoModel : BlazorComponent
    {
        protected static string message { get; set; }

        protected void CallJSMethod()
        {
            JSRuntime.Current.InvokeAsync<bool>("JSMethod");
        }
    }
}

The method CallJSMethod will call our JS function “JSMethod” by using “JSRuntime.Current.InvokeAsync” method. This method can take two parameters — the JS function name and any parameter that needed to be supplied to theJS function. In this case, we are not passing any parameter to JS function.

CallJSMethod方法将使用“ JSRuntime.Current.InvokeAsync”方法调用我们的JS函数“ JSMethod”。 此方法可以使用两个参数-JS函数名称和需要提供给JS函数的任何参数。 在这种情况下,我们没有将任何参数传递给JS函数。

Open JSDemo.cshtml and put in the following code:

打开JSDemo.cshtml 并输入以下代码:

@page "/demo"
@using BlazorJSDemo.Pages

@inherits JSDemoModel  

<h1>JavaScript Interop Demo</h1>

<hr />

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

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

Here we have defined the route of the page at the top. So, in this application, if we append “/demo” to the base URL, then we will be redirected to this page. We are also inheriting the JSDemoModel class, which is defined in the JSDemo.cshtml.cs file. This will allow us to use the methods defined in the JSDemoModel class.

在这里,我们在顶部定义了页面的路由。 因此,在此应用程序中,如果我们在基本URL后面附加“ / demo”,那么我们将被重定向到此页面。 我们还将继承JSDemoModel类,该类在JSDemo.cshtml.cs文件中定义。 这将使我们能够使用JSDemoModel类中定义的方法。

After this, we have defined a button. This button will invoke the “CallJSMethod” method when clicked. The <p> element with id “demop” is also defined, and its value will be set by the JS function “JSMethod”.

此后,我们定义了一个按钮。 单击此按钮将调用“ CallJSMethod”方法。 还定义了ID为“ demop”的<p>元素,其值将由JS函数“ JSMethod”设置。

从JavaScript调用C / .NET方法 (Calling a C/.NET method from JavaScript)

Now we will define our JS Method in the wwwroot/index.html file, which will call our C# method in the JSDemo.cshtml.cs file.

现在,我们将在wwwroot / index.html文件中定义JS方法,该文件将在JSDemo.cshtml.cs中调用C#方法。 文件。

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

从JavaScript调用C#方法的语法如下:

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

Therefore, we will follow the same method calling syntax. Open the wwwroot/index.html file and add the following script section to it:

因此,我们将遵循相同的方法调用语法。 打开wwwroot / index.html文件,并在其中添加以下脚本部分:

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

Here we are defining a JS function “CSMethod”. This function will have a call back to our C# method “CSCallBackMethod” which is defined in JSDemoModel class.

在这里,我们定义了一个JS函数“ CSMethod”。 该函数将调用在JSDemoModel类中定义的C#方法“ CSCallBackMethod”。

To invoke a C#/.NET method from JavaScript, the target .NET method must meet the following criterias:

要从JavaScript调用C#/。NET方法,目标.NET方法必须满足以下条件:

  1. The method needs to be Static.

    该方法必须是静态的。
  2. It must be Non-generic.

    它必须是非泛型的。
  3. The method should have no overloads.

    该方法应该没有重载。
  4. It has concrete JSON serializable parameter types.

    它具有具体的JSON可序列化参数类型。
  5. It must be decorated with [JSInvokable] attribute.

    必须用[JSInvokable]属性修饰。

Open JSDemo.cshtml.cs file and add the following code inside the JSDemoModel class.

打开JSDemo.cshtml.cs 文件,并在JSDemoModel类内添加以下代码。

protected static string message { get; set; }

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

protected void CallCSMethod()
{
  JSRuntime.Current.InvokeAsync<bool>("CSMethod");
}

Here we have defined two methods:

这里我们定义了两种方法:

  1. CallCSMethod: This will call our JS function “CSMethod”

    CallCSMethod :这将调用我们的JS函数“ CSMethod”

  2. CSCallBackMethod: This is a static method and it will be invoked from the JavaScript function “CSMethod”. Hence it is decorated with[JSInvokable] attribute. This method will set the value of a string variable message, which will be displayed on the UI.

    CSCallBackMethod :这是一个静态方法,将从JavaScript函数“ CSMethod”中调用。 因此,它用[JSInvokable]属性修饰。 此方法将设置字符串变量message的值,该值将显示在UI上。

Open the JSDemo.cshtml file and add the following code to it:

打开JSDemo.cshtml 文件,并向其中添加以下代码:

<button class="btn btn-primary" onclick="@CallCSMethod">Call C# Method</button>
<br />
<p>@message</p>

Here we have defined a button which will call the “CallCSMethod” method on the “onclick” event. The value of the variable message is set on the button click.

在这里,我们定义了一个按钮,该按钮将在“ onclick”事件上调用“ CallCSMethod”方法。 变量消息的值在单击按钮时设置。

Open \BlazorJSDemo\Shared\NavMenu.cshtml page and put the following code into it. This will include a link to our JSDemo.cshtml page in the navigation menu.

打开\ BlazorJSDemo \ Shared \ NavMenu.cshtml 页面并将以下代码放入其中。 这将包含指向我们的JSDemo.cshtml的链接 导航菜单中的页面。

<div class="top-row pl-4 navbar navbar-dark">
    <a class="navbar-brand" href="">BlazorJSDemo</a>
    <button class="navbar-toggler" onclick=@ToggleNavMenu>
        <span class="navbar-toggler-icon"></span>
    </button>
</div>

<div class=@(collapseNavMenu ? "collapse" : null) onclick=@ToggleNavMenu>
    <ul class="nav flex-column">
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="" Match=NavLinkMatch.All>
                <span class="oi oi-home" aria-hidden="true"></span> Home
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="counter">
                <span class="oi oi-plus" aria-hidden="true"></span> Counter
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="fetchdata">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
            </NavLink>
        </li>
         <li class="nav-item px-3">
            <NavLink class="nav-link" href="demo">
                <span class="oi oi-list-rich" aria-hidden="true"></span> JS Demo
            </NavLink>
        </li>
    </ul>
</div>

@functions {
    bool collapseNavMenu = true;

    void ToggleNavMenu()
    {
        collapseNavMenu = !collapseNavMenu;
    }
}

执行演示 (Execution demo)

Navigate to View >> Integrated Terminal to open the terminal window.

导航到查看>>集成终端以打开终端窗口。

Type the command dotnet run to start the application. Refer to the image below:

键入命令dotnet run启动应用程序。 请参考下图:

You can observe that the application is listening on http://localhost:5000. Open any browser on your machine and navigate to this URL. You can see the application home page. Click on the “JS Demo” link in the navigation menu to open the JSdemo view. Notice the URL has “/demo” appended to it.

您可以观察到该应用程序正在侦听http:// localhost:5000。 打开计算机上的任何浏览器,然后导航到该URL。 您可以看到应用程序主页。 单击导航菜单中的“ JS Demo”链接以打开JSdemo视图。 请注意,URL后面附加了“ / demo”。

Click on the buttons to invoke the JS functions and C# method.

单击按钮以调用JS函数和C#方法。

Refer to the GIF below.

请参阅下面的GIF。

结论 (Conclusion)

In this article, we have learned about JavaScript Interop. We have also created a sample application to demonstrate how JavaScript Interop works with the Blazor framework.

在本文中,我们了解了JavaScript Interop。 我们还创建了一个示例应用程序,以演示JavaScript Interop如何与Blazor框架一起使用。

Please get the source code from Github and play around to get a better understanding.

请从Github获取源代码,并进行尝试以获得更好的理解。

Get my book Blazor Quick Start Guide to learn more about Blazor.

获取我的书《 Blazor快速入门指南》,以了解有关Blazor的更多信息。

You can check out my other articles on ASP .NET Core here.

您可以在此处查看有关ASP.NET Core的其他文章。

也可以看看 (See Also)

Originally published at ankitsharmablogs.com

最初发布在ankitsharmablogs.com

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

interop

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值