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
重要的提示
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文件中。
Always add your custom <script> tag after “ <script src=”_framework/blazor.webassembly.js”></script>” in the <body> 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方法必須滿足以下條件:
- The method needs to be Static. 該方法必須是靜態的。
- It must be Non-generic. 它必須是非泛型的。
- The method should have no overloads. 該方法應該沒有重載。
- It has concrete JSON serializable parameter types. 它具有具體的JSON可序列化參數類型。
- 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:
這里我們定義了兩種方法:
CallCSMethod: This will call our JS function “CSMethod”
CallCSMethod :這將調用我們的JS函數“ CSMethod”
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”方法。 變量消息的值在單擊按鈕時設置。
將鏈接添加到導航菜單 (Adding Link to Navigation menu)
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)
ASP.NET Core — Getting Started With Blazor
ASP.NET Core — Blazor入門
ASP.NET Core — CRUD Using Blazor And Entity Framework Core
ASP.NET Core —使用Blazor和Entity Framework Core的CRUD
Creating a SPA Using Razor Pages With Blazor
使用帶有Blazor的Razor頁面創建SPA
Cascading DropDownList In Blazor Using EF Core
使用EF Core在Blazor中級聯DropDownList
Deploying A Blazor Application On IIS
在IIS上部署Blazor應用程序
Originally published at ankitsharmablogs.com
最初發布在ankitsharmablogs.com
翻譯自: https://www.freecodecamp.org/news/how-to-implement-javascript-interop-in-blazor-9f91d263ec51/
interop