Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array of strings from JS to C# inside WebBrowser control

I'm using ObjectForScripting property to interact with web page inside WebBrowser control and everything works fine except I can't figure out how to pass array of strings back to C#

HTML code

<input type="submit" onclick="window.external.save(Array('test', 'test2'))" />

Form

// Returns System.__ComObject
public void Save(object parameters)
{
}

// Throws an exception
public void Save(object[] parameters)
{
}

// Also throws an exception
public void Save(string[] parameters)
{
}
like image 458
Sergej Andrejev Avatar asked Sep 23 '10 09:09

Sergej Andrejev


People also ask

How do you pass an array of strings?

Passing Array To The Method In Java To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);

Can you pass an array 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.

Can you have an array of strings in JavaScript?

JavaScript support various types of array, string array is one of them. String array is nothing but it's all about the array of the string. The array is a variable that stores the multiple values of similar types. In the context of a string array, it stores the string value only.


2 Answers

Rather than fight it; maybe approach the problem from another angle... could you (instead, either of):

  • delimit the data (with Array.join) and pass a single string, and split it (string.Split) in the C#
  • call Save multiple times, accepting a single string each time (Save(string s)), then call a final method to actually commit the changes
like image 167
Marc Gravell Avatar answered Sep 24 '22 00:09

Marc Gravell


You can use an anonymous object instead of an array on the javascript side:

<input type="submit" onclick="window.external.save({first: 'test', second: 'test2'})" />

On the C# side (you need to use .NET 4.0 or more for the dynamic or use Type.InvokeMember if you are on an older version):

public void Save(dynamic parameters)
{
  MessageBox.Show(parameters.first);
  MessageBox.Show(parameters.second); 
}

Not tested, but I think you can use reflection to discover the members.

Also look at this: http://dotnetacademy.blogspot.fr/2009/11/vbnetcnet-communication-with-javascript.html

like image 42
Maxence Avatar answered Sep 21 '22 00:09

Maxence