7

I'm trying to call a C# method from JavaScript by using ActiveXObject:

var myobj = new ActiveXObject('myobject');
var arr = myobj.GetArray();

Eventually, arr will contain a SAFEARRAY object, but not JScript array. Is there any way to return native JavaScript object from a C# method?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Pavel Podlipensky
  • 8,201
  • 5
  • 42
  • 53

4 Answers4

8

You can return a JSON string and then parse into a JavaScript object. There are a number of .NET libraries available to serialize .NET objects into JSON and vice-versa-

to name a few.

This question and answer may be of use to you

Community
  • 1
  • 1
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
  • No, this is not the case. I know that similar possible and actually was done by my colleague by using C++, but I'm not familiar with that, so I wish to know how can I do it by using C#. – Pavel Podlipensky Mar 16 '09 at 08:07
5

I found the solution by myself, but no documentation exists for this part. The solution is to use JScript.ArrayObject in the following way:

ArrayObject _lastField;
byte[] byteArray = new byte[]{2,1,2,3};
object[] array = new object[byteArray.Length];
byteArray.CopyTo(array, 0);
_lastField = Microsoft.JScript.GlobalObject.Array.ConstructArray(array);

After that you will be able to use the _lastField array in JavaScript like a native array:

var myobj = new ActiveXObject('myobject');
var arr = myobj.LastField;
alert(arr[1]);
George Stocker
  • 57,289
  • 29
  • 176
  • 237
Pavel Podlipensky
  • 8,201
  • 5
  • 42
  • 53
  • 2
    I would be extremely wary of this. It's quite likely MS are going to hand you xbrowser issues given the "JScript" and the ActiveX. The JSON approach is going to be more flexible and more reliable imho. – annakata Mar 16 '09 at 09:14
1

You may return delimited Joined String in C# and can split into JavaScript

//C#
public string getArryString()
{
string[] arrstring = new string[]{"1","2","3"};
return string.Join(",", arrstring);
}

//Javascript
var arrstring = objActiveX.getArryString().split(',');
Raj kumar
  • 1,275
  • 15
  • 20
0

Via VBArray it can work like this:

  1. Return object[] from C# (declare so in the dispinterface).

  2. To get a native JS array in JScript use VBArray:

    var jsArray = new VBArray(myobj.GetArray()).toArray();
    for (i = 0; i < jsArray.length; i++) 
    {
       // use jsArray[i]
    }
    

Background information:

Martin Schmidt
  • 1,331
  • 10
  • 5