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)

  • 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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393736.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393736.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393736.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Centos 7和 Centos 6開放查看端口 防火墻關閉打開

Centos 7 firewall 命令&#xff1a; 查看已經開放的端口&#xff1a; firewall-cmd --list-ports 開啟端口 firewall-cmd --zonepublic --add-port80/tcp --permanent 命令含義&#xff1a; –zone #作用域 –add-port80/tcp #添加端口&#xff0c;格式為&#xff1a;端口/通訊…

和get redis_SpringBoot整合Redis,你get了嗎?

Our-task介紹本篇博客是我github上our-task&#xff1a;一個完整的清單管理系統的配套教程文檔&#xff0c;這是SpringBootVue開發的前后端分離清單管理工具&#xff0c;仿滴答清單。目前已部署在阿里云ECS上&#xff0c;可進行在線預覽&#xff0c;隨意使用&#xff08;附詳細…

linux課程設計qq,仿QQ聊天系統課程設計.doc

目錄緒論1一&#xff0e;需求分析11.1軟件功能需求分析21.2 安全需求分析2二&#xff0e;總體設計32.1 軟件結構圖32.2 功能描述32.2.1注冊功能概要42.2.2登錄功能概要42.2.3聊天功能概要52.3 安全設計6三&#xff0e;數據庫設計63.1概念結構設計63.2邏輯結構設計73.3物理結構設…

ocp linux 基礎要點

基本命令&#xff1a; 創建/修改/刪除用戶 useradd/usermod/userdel 創建/修改/刪除用戶組 groupadd/groupmod/groupdel 修改所屬用戶/所屬用戶組 chown/chgrp 修改權限 chmod 創建文件夾 mkdir 創建文件 touch 切換目錄 …

leetcode1386. 安排電影院座位(貪心)

如上圖所示&#xff0c;電影院的觀影廳中有 n 行座位&#xff0c;行編號從 1 到 n &#xff0c;且每一行內總共有 10 個座位&#xff0c;列編號從 1 到 10 。 給你數組 reservedSeats &#xff0c;包含所有已經被預約了的座位。比如說&#xff0c;researvedSeats[i][3,8] &…

首席技術執行官_如何在幾分鐘內找到任何首席執行官的電子郵件地址

首席技術執行官by Theo Strauss由西奧斯特勞斯(Theo Strauss) 如何在幾分鐘內找到任何首席執行官的電子郵件地址 (How to find any CEO’s email address in minutes) 銀河電子郵件指南&#xff1a;第一部分 (The Emailer’s Guide To The Galaxy: Part I) I’m 17, so my net…

Linux 查看磁盤或文件夾及文件大小

當磁盤大小超過標準時會有報警提示&#xff0c;這時如果掌握df和du命令是非常明智的選擇。 df可以查看一級文件夾大小、使用比例、檔案系統及其掛入點&#xff0c;但對文件卻無能為力。 du可以查看文件及文件夾的大小。 兩者配合使用&#xff0c;非常有效。比如用df查看哪個…

Python列表基礎

列表&#xff1a;創建列表:list[] 注意&#xff1a;列表里面類型可以是不同的類型 取值&#xff1a;list[2]   替換&#xff1a;注意不要越界(下表超出了可表示范圍) 操作&#xff1a; 合并列表&#xff1a;   list3list2list1 列表的重復:   (list8*3)   判斷元素是否…

樹莓派 觸摸屏_如何用樹莓派搭建一個顆粒物(PM2.5)傳感器

用樹莓派、一個廉價的傳感器和一個便宜的屏幕監測空氣質量。-- Stephan Tetzel(作者)大約一年前&#xff0c;我寫了一篇關于如何使用樹莓派和廉價傳感器測量 空氣質量 的文章。我們這幾年已在學校里和私下使用了這個項目。然而它有一個缺點&#xff1a;由于它基于無線/有線網&a…

shell 25個常用命令

1.列出所有目錄使用量&#xff0c;并按大小排序。 ls|xargs du -h|sort -rn #不遞歸下級目錄使用du -sh2.查看文件排除以#開關和空白行&#xff0c;適合查看配置文件。 egrep -v "^#|^$" filenamesed /#.*$/d; /^ *$/d3.刪除空格和空行。 sed /^$/d filename #刪除空…

tensorflow入門_TensorFlow法律和統計入門

tensorflow入門by Daniel Deutsch由Daniel Deutsch TensorFlow法律和統計入門 (Get started with TensorFlow on law and statistics) What this is about 這是關于什么的 What we will use 我們將使用什么 Get started 開始吧 Shell commands for installing everything you …

centos7 nginx+php5.6+mysql安裝與配置

安裝與配置 php 56的安裝 php的配置寫在 php.ini&#xff0c;可在phpinfo()中查看 //查找已安裝 yum list installed | grep php // php卸載 yum -y remove php56* yum remove httpd* php* 可用的資源&#xff1a;centos 安裝php56nginx nginx php-fpm nginx安裝 sudo rpm -Uv…

leetcode337. 打家劫舍 III(dfs)

在上次打劫完一條街道之后和一圈房屋后&#xff0c;小偷又發現了一個新的可行竊的地區。這個地區只有一個入口&#xff0c;我們稱之為“根”。 除了“根”之外&#xff0c;每棟房子有且只有一個“父“房子與之相連。一番偵察之后&#xff0c;聰明的小偷意識到“這個地方的所有房…

c語言面試題東軟,2012東軟筆試題

1、下列變量定義錯誤的是&#xff24;int a;double b4.5;boolean btrue;float f9.8; (9.8f)2、65%32的值是 D 3%53219103、對于一個三位的正整數 n&#xff0c;取出它的十位數字k(k為整型)的表達式是k n / 10 % 10k ( n - n / 100 * 100 )k n % 10k n / 104、下列語句序列執…

matlab肌電信號平滑濾波_MATLAB圖像處理:43:用高斯平滑濾波器處理圖像

本示例說明了如何使用imgaussfilt來對圖像應用不同的高斯平滑濾波器。高斯平滑濾波器通常用于降低噪聲。將圖像讀入工作區。I imread(cameraman.tif);使用各向同性的高斯平滑核增加標準偏差來過濾圖像。高斯濾波器通常是各向同性的&#xff0c;也就是說&#xff0c;它們在兩個…

Github 簡明教程 - 添加遠程庫

現在的情景是&#xff0c;你已經在本地創建了一個Git倉庫后&#xff0c;又想在GitHub創建一個Git倉庫&#xff0c;并且讓這兩個倉庫進行遠程同步&#xff0c;這樣&#xff0c;GitHub上的倉庫既可以作為備份&#xff0c;又可以讓其他人通過該倉庫來協作&#xff0c;真是一舉多得…

githooks_使用Githooks改善團隊的開發工作流程

githooksby Daniel Deutsch由Daniel Deutsch 使用Githooks改善團隊的開發工作流程 (Improve your team’s development workflow with Githooks) Every product that is developed by more than one programmer needs to have some guidelines to harmonize the workflow.由多…

分享AI有道干貨 | 126 篇 AI 原創文章精選(ML、DL、資源、教程)

一年多來&#xff0c;公眾號【AI有道】已經發布了 140 的原創文章了。內容涉及林軒田機器學習課程筆記、吳恩達 deeplearning.ai 課程筆記、機器學習、深度學習、筆試面試題、資源教程等等。值得一提的是每篇文章都是我用心整理的&#xff0c;編者一貫堅持使用通俗形象的語言給…

c語言qt生成dll與加載dll,Qt制作界面的DLL以及調用

1、將界面做成dll修改pro文件DEFINES WIDGETDLL_LIBRARYTEMPLATE lib修改頭文件#if defined(WIDGETDLL_LIBRARY)# define WIDGETDLLSHARED_EXPORT Q_DECL_EXPORT#else# define WIDGETDLLSHARED_EXPORT Q_DECL_IMPORT#endifclass WIDGETDLLSHARED_EXPORT WidgetDll:public QWi…

leetcode1338. 數組大小減半(貪心算法)

給你一個整數數組 arr。你可以從中選出一個整數集合&#xff0c;并刪除這些整數在數組中的每次出現。 返回 至少 能刪除數組中的一半整數的整數集合的最小大小。 示例 1&#xff1a; 輸入&#xff1a;arr [3,3,3,3,5,5,5,2,2,7] 輸出&#xff1a;2 解釋&#xff1a;選擇 {3…