Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a JavaScript 'native' array from a C# method?

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?

like image 941
Pavel Podlipensky Avatar asked Mar 15 '09 12:03

Pavel Podlipensky


3 Answers

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-

  • JSON.NET
  • Microsoft ASP.NET AJAX library
  • JSONSharp

to name a few.

This question and answer may be of use to you

like image 181
Russ Cam Avatar answered Nov 04 '22 23:11

Russ Cam


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]);
like image 22
Pavel Podlipensky Avatar answered Nov 04 '22 21:11

Pavel Podlipensky


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(',');
like image 1
Raj kumar Avatar answered Nov 04 '22 21:11

Raj kumar