C#背景程式與HTML頁面中JS方法互調(功能類似於Ajax中的DWR)

來源:互聯網
上載者:User

標籤:class   ext   com   使用   strong   string   

此方法適用於 C#中嵌入WebBrowser(瀏覽器) 通過瀏覽器中載入的頁面與C#的後台代碼進行互動。

一、C#程式

1、在C#表單中添加WebBrowser(瀏覽器),將頁面的URL添加到瀏覽器中。

2、表單代碼添加 using System.Runtime.InteropServices;//和Html頁面互動使用

在類的上一行添加 [ComVisible(true)]//和Html頁面互動使用

在類的構造其中添加

this.webB.ObjectForScripting = this; //和Html頁面互動使用

如:

using System.Runtime.InteropServices;

namespace slgdjb {     [ComVisible(true)]     public partial class Frm_Index : Form     {         public Frm_Index()         {             InitializeComponent();             this.webB.ObjectForScripting = this;          }

   }

}

3、添加供Html頁面調用的方法

如:

該方法的方法名即為Html頁面JS中所要調用的方法名 

public string myAction(object para) {   //方法內容在此寫           }

4、C#程式調用Html頁面JS方法

首先要獲得Html頁面的Document,然後再調用Html頁面的JS方法

如:

HtmlDocument doc = webB.Document; string[] objArray = new string[2]; objArray[0] = "a";

objArray[1] = "b"; //調用Html頁面js方法,JSMonth為JS方法名,objArray為傳遞的參數。

//JS中不能接收對象,但可以接收整形、字串、字串數組。 doc.InvokeScript("JSMonth",objArray);

 

二、Html頁面中JS方法調用C#方法

1、在Html頁面JS中調用C#程式的方法,若C#中的方法有傳回值,則JS可以得到。

如:

//myAction為C#中方法的方法名,para為該方法的參數。

var str = window.external.myAction(para); 

2、供C#調用的Html頁面中JS的方法

該方法的方法名即為C#中所要調用的方法名  obj即為要傳遞的參數。若傳遞的參數為數組,則在JS

方法中可直接使用arguments[index(數組參數編號)]表示數組的參數值。arguments為JS預設數組參數,其好處在於JS方法不必寫傳遞的參數。

function JSMonth(obj){

//若obj為數組,則obj[0]等價於arguments[0];其方法名可改寫為JSMonth()

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.