开发者

Call javascript from c# using C# 4.0 Dynamic feature

Is it possible to call javascript from c# something like this?

ScriptRuntime py = Python.CreateRunt开发者_JS百科ime();
dynamic random = py.UseFile("cal.js");
var result =random.Add(1,2);

cal.js


 function Add(a, b) {

        return (a + b);
    }


Yes, as long as you host the js in a webrowser control. You can use the ObjectForScripting and document properties for this along with a com visible object. Indeed the opposite is true as well, that is you can call c# methods from JavaScript. The type dynamic allow you to pass, and work with, complex objects without having to use reflection Invoke/GetProperty, etc.

Here is a really simple example.

[ComVisibleAttribute(true)]
public class Ofs
{
   public void MethodA(string msg)
   {
      MessageBox.Show(msg); // hello from js!
   }
}

public class Form1
{

  void Form1()
  {
    WebBrowser b = new WebBrowser();
    b.DocumentText = "<script>"
      + "var a = [];"
      + "a.foo = 'bar!'";
      + "var jsFunc=function(y){alert(y);}"
      + "var jsFunc2=function(){return a;}"
      + "window.external.MethodA('hello from js!');</script>";

    b.ObjectForScripting = new Ofs(); // we can call any public method in Ofs from js now...
    b.Document.InvokeScript("jsFunc", new string[] { "hello!" }); // we can call the js function
    dynamic a = (dynamic)b.Document.InvokeScript("jsFunc2"); // c#'a' is js'a'
    string x = a.foo;
    MessageBox.Show(x); // bar!
  }
}


Yes it is possible to call Javascript code from C#, but not by using dynamic types.

Instead, you can leverage JScript.Net's eval functionality for this.

The following article has the basics of doing this:

http://odetocode.com/Code/80.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜