[英]Calling a c# function (.cs file) from a javascript file(.js file)
I have a javascript file and I have a method "Test" in that method I like to call ac# function. 我有一个javascript文件,并且在该方法中有一个方法“ Test”,我想调用ac#函数。
The c# function is not in the same file as in the javascript file. c#函数与javascript文件不在同一个文件中。
It's in a .cs file. 在.cs文件中。 So how can I manage that the javascript functions is able to call the c# function ?
那么,如何管理javascript函数能够调用c#函数呢?
I already searched on the internet but most solutions are based on a aspx and apx.cs file... 我已经在互联网上进行搜索,但是大多数解决方案都基于apx和apx.cs文件...
I tried something like this: 我尝试过这样的事情:
viewer.js viewer.js
function Test() {
alert("Hello world-2");
window.external.MethodToCallFromScript();
}
ScriptManager.cs ScriptManager.cs
[ComVisible(true)]
public class ScriptManager
{
public void MethodToCallFromScript()
{
Debug.WriteLine("test");
}
}
But it did not work... 但这没有用...
Can somebody help me? 有人可以帮我吗?
Thanks! 谢谢!
In order to have this working, you must set the ObjectForScripting
-property of the WebBrwoser
-control. 为了这个工作,你必须设置
ObjectForScripting
中的-property WebBrwoser
-控制。
Here is an example 这是一个例子
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" });
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.