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?
Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.
To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.
Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.
A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun().
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With