从javascript文件(.js文件)调用c#函数(.cs文件)

时间:2013-04-03 10:49:45

标签: c# javascript

我有一个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");
        }
    }

但它没有用......

有人能帮助我吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

为了使其正常工作,您必须设置ObjectForScripting - WebBrwoser - 属性。{/ p>

这是一个例子

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" });
    }

}

here是链接。