Pass an array from javascript to C # in Metro app

EDIT: I found the answer (using Tejs); see below.


I am developing a Metro application using HTML / Javascript, as well as some helper libraries in C #. Generally speaking, I have a lot of success calling C # methods from Javascript, but I can't get the transfer arrays (in my particular case, string arrays) to work. Passing single lines without problems.

My code looks something like this:

// in javascript project var string1 = ...; var string2 = ...; var string3 = ...; var result = MyLibrary.MyNamespace.MyClass.foo([string1, string2, string3]); 

Then in C #:

 // in C# project public sealed class MyClass { public static string Foo(string[] strings) { // do stuff... } } 

The problem is that the "Foo" method gets an array with the correct length (therefore, in the above example, 3), but all the elements are empty. I also tried this:

 public static string Foo(object[] strings) { ... 

That didn't work either - the array was correct, but all elements were null.

I tried passing string literals, string variables using "new Array (...)" in javascript, changing the signature of "Foo" to "params string []" and "params object []", all to no avail.

Since passing single lines works fine, I can probably get around this with some hackers ... but it looks like this should work. It seems strange to me that the array is passed as the correct size (i.e., everything that marshaling does knows SOMETHING about the structure of the javascript array), and yet the contents are not populated.

+8
javascript c # windows-8 windows-runtime
source share
2 answers

The trick is to use IEnumerable instead of the string []. So replace my source code as follows:

 public sealed class MyClass { public static string Foo(IEnumerable<string> strings) { // do stuff... } } 

Also note that IEnumerable also works if you need to pass arrays of something other than strings.

Thanks @Tejs for the inspiration!

+1
source share

The solution to your problem is very simple, you just need to pay attention to it. First you have to accept the fact that in C # (and quite possibly javascript) there also cannot be an array of arrays (at least not the way you do it!) So, in your javascript:

var result = MyLibrary.MyNamespace.MyClass.foo ([string1, string2, string3]);

and in your C #:

public static string Foo (string []) {

you will need to allow the Foo method to pass several arguments to string arrays, for example:

public static string Foo (string [] string1, string [] string2, string [] string3) {

But if you want to create an array of arrays, you will have to use the List constructor:

public static string Foo (List <string []> string) {

But the problem with the answer above is that Javascript does not have a list constructor, so I suggest moving on to the first solution, unless you find a way to fix this!

+2
source share

All Articles