Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 338
anthonyvd Avatar asked Jul 08 '11 04:07

anthonyvd


People also ask

How do you pass an array to a function in JavaScript?

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.

How arrays are passed to functions in C?

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.

What is the correct way to JavaScript array?

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.

How an array can be passed through function?

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().


1 Answers

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

like image 135
Ilia Choly Avatar answered Sep 21 '22 12:09

Ilia Choly