为了账号安全,请及时绑定邮箱和手机立即绑定

如何通过 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# 方法的返回值

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

查看完整回答
反对 回复 2023-04-20
  • 1 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信