亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過 webBrowser 控件將數據從 C# 服務器端傳遞到 htm?

如何通過 webBrowser 控件將數據從 C# 服務器端傳遞到 htm?

守著星空守著你 2023-04-20 10:22:18
我在通過 javascript 將字符串傳遞到 HTML 頁面時遇到問題。我有一個窗口窗體,一個 HTML 文件,其中包含我的 Javascript 和 HTML 代碼。在 C# 頁面中的函數中,我有一個字符串需要通過 javascript 發送到 HTML 頁面。但我不能通過它。請建議我。謝謝下面是我的 C# 方法代碼    private void Form1_Load(object sender, EventArgs e)        {        Assembly assembly = Assembly.GetExecutingAssembly();        StreamReader reader = new StreamReader(assembly.GetManifestResourceStream("ProjectName.Maps.html"));        webBrowser1.DocumentText = reader.ReadToEnd();        ***//pass getDefaultMap() value (str) to the javascript in Maps.html page.***        }    private string getDefaultMap()        {        string str;        str = (@"Exec SP_Map_Display @Opt=1");                    return str ;        }我的 HTML 頁面如下<body><script>    $(document).ready(function () {        $("#btnSubmit").click(function () {         ***// Get the data from C# code str***    }</script>    <input type="button" name="btnSubmit" value="Submit" /><div id="dvMap"></div></body>
查看完整描述

1 回答

?
慕容708150

TA貢獻1831條經驗 獲得超4個贊

假設這是 WinForms,因為有一個 WebBrowser 控件,從 HTML 頁面 JavaScript 調用 C# 代碼可以用這個最小的例子來完成:


將簡單的 HTML 頁面添加到項目的根目錄并Properties設置為此Copy to Output Directory: Copy if newer將確保有一個簡單的頁面用于測試:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <meta charset="utf-8" />

    <title>WebForms WebBrowser Control Client</title>

</head>

<body>

    <input type="button" onclick="getLocations()" value="Call C#" />

    <script type="text/javascript">

        function getLocations() {

            var locations = window.external.SendLocations();

            alert(locations);

        }

    </script>

</body>

</html>

JS函數getLocations會調用C#方法SendLocations,重要的部分是Form1類注解和設置webBrowser1.ObjectForScripting = this:


using System.Windows.Forms;

using System.Security.Permissions;

using System.IO;


[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]

[System.Runtime.InteropServices.ComVisibleAttribute(true)]

public partial class Form1 : Form

{

    public Form1()

    {

        InitializeComponent();

    }


    private void Form1_Load(object sender, EventArgs e)

    {

        webBrowser1.ObjectForScripting = this;


        var path = Path.GetFullPath("Client.html");

        var uri = new Uri(path);

        webBrowser1.Navigate(uri);

    }


    public string SendLocations()

    {

        return "SF, LA, NY";

    }

}

單擊 HTML 按鈕Call C#將顯示一個彈出窗口,其中包含 C# 方法的返回值

http://img1.sycdn.imooc.com//6440a2030001481d06570452.jpg

查看完整回答
反對 回復 2023-04-20
  • 1 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號