How should an array be passed to a Javascript function from C#?

Anthony Vallée-Dubois picture Anthony Vallée-Dubois · Jul 8, 2011 · Viewed 10.3k times · Source

I use a WebBrowser object from WPF and I'm calling some Javascript code in the page loaded in the browser like this:

myWebBrowser.InvokeScript("myJsFunc", new object[] { foo.Text, bar.ToArray<string>()});

Now, the js function is supposed to iterate over the elements of the second parameter (an array of strings) and do stuff accordingly. The only issue is that the parameter seems not to be passed as a js array.

For example,

alert(typeof theArray);

alerts "Unknown".

What is the proper way to pass an array as a parameter when invoking a js function from CSharp?

Answer

Ilia Choly picture Ilia Choly · Jul 8, 2011

Maybe pass it as a json string instead and parse it in the js function

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var json = serializer.Serialize(bar.ToArray<string>());

myWebBrowser.InvokeScript("myJsFunc", new object[] { foo.Text, json });

js:

function myJsFunc(json) {
   var data = JSON.parse(json);
   // do something with it.
}

http://blogs.microsoft.co.il/blogs/pini_dayan/archive/2009/03/12/convert-objects-to-json-in-c-using-javascriptserializer.aspx