猿问

如何通过 webBrowser 控件将数据从 C# 服务器端传递到 htm?

我在通过 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>


守着星空守着你
浏览 124回答 1
1回答

慕容708150

假设这是 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>&nbsp; &nbsp; <meta charset="utf-8" />&nbsp; &nbsp; <title>WebForms WebBrowser Control Client</title></head><body>&nbsp; &nbsp; <input type="button" onclick="getLocations()" value="Call C#" />&nbsp; &nbsp; <script type="text/javascript">&nbsp; &nbsp; &nbsp; &nbsp; function getLocations() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var locations = window.external.SendLocations();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(locations);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </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{&nbsp; &nbsp; public Form1()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; InitializeComponent();&nbsp; &nbsp; }&nbsp; &nbsp; private void Form1_Load(object sender, EventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; webBrowser1.ObjectForScripting = this;&nbsp; &nbsp; &nbsp; &nbsp; var path = Path.GetFullPath("Client.html");&nbsp; &nbsp; &nbsp; &nbsp; var uri = new Uri(path);&nbsp; &nbsp; &nbsp; &nbsp; webBrowser1.Navigate(uri);&nbsp; &nbsp; }&nbsp; &nbsp; public string SendLocations()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return "SF, LA, NY";&nbsp; &nbsp; }}单击 HTML 按钮Call C#将显示一个弹出窗口,其中包含 C# 方法的返回值
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答