从javascript文件(.js文件)调用c#函数(.cs文件)
Calling a c# function (.cs file) from a javascript file(.js file)
我有一个javascript文件,我有一个方法"Test"在这个方法中,我喜欢调用c#函数。
c#函数和javascript文件不在同一个文件中
在。cs文件中。那么我如何管理javascript函数能够调用c#函数呢?
我已经在互联网上搜索过了,但大多数解决方案都是基于aspx和apx.cs文件…
我试过这样做:
viewer.js
function Test() {
alert("Hello world-2");
window.external.MethodToCallFromScript();
}
ScriptManager.cs
[ComVisible(true)]
public class ScriptManager
{
public void MethodToCallFromScript()
{
Debug.WriteLine("test");
}
}
但它没有工作…
有人能帮我吗?
谢谢!
为了使其工作,您必须设置WebBrwoser
-控件的ObjectForScripting
-属性。
下面是一个例子
using System;
using System.Windows.Forms;
using System.Security.Permissions;
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Form1 : Form
{
private WebBrowser webBrowser1 = new WebBrowser();
private Button button1 = new Button();
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
public Form1()
{
button1.Text = "call script code from client code";
button1.Dock = DockStyle.Top;
button1.Click += new EventHandler(button1_Click);
webBrowser1.Dock = DockStyle.Fill;
Controls.Add(webBrowser1);
Controls.Add(button1);
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.AllowWebBrowserDrop = false;
webBrowser1.IsWebBrowserContextMenuEnabled = false;
webBrowser1.WebBrowserShortcutsEnabled = false;
webBrowser1.ObjectForScripting = this;
// Uncomment the following line when you are finished debugging.
//webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.DocumentText =
"<html><head><script>" +
"function test(message) { alert(message); }" +
"</script></head><body><button " +
"onclick='"window.external.Test('called from script code')'">" +
"call client code from script code</button>" +
"</body></html>";
}
public void Test(String message)
{
MessageBox.Show(message, "client code");
}
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("test",
new String[] { "called from client code" });
}
}
链接在这里
相关文章:
- 通过Ajax将JavaScript函数传递给PHP文件
- 在不破坏未定义函数的情况下,对多个视图使用单个js文件
- 如何在 javascript 文件函数中找到 Radnotification id
- 对另一个文件函数的引用
- 从代码隐藏调用.js文件函数
- 如何javascript调用iframe加载的文件函数
- Javascript外部文件函数赢得'我以前不工作
- 读取本地文本文件函数不返回字符串类型,而是返回一个void类型
- 如何使用javascript在同一位置编辑和保存计算机中的任何文本文件.函数调用时,
- 如何用javascript调用jar文件函数
- 从SharePoint 2013脚本编辑器调用外部javascript文件函数
- 优先使用JS文件函数而不是HTML文件
- 如何从页面后面的代码调用js文件函数
- 外部JS文件's函数在无限滚动后不加载
- 在HTML按钮点击事件上调用jquery文件函数
- 在Angular js控制器中调用外部js文件函数
- Webpack主javascript文件's函数不能在加载在页脚的js文件中访问
- 我的jquery文档准备函数不能识别外部js文件函数
- 调用selenium-ide中的js文件函数
- 在RegisterStartupScript方法中使用外部Javascript文件函数