Pass Array From C# COM object to JavaScript?

2020-02-29 06:28发布

Similar to this How do I return an array of strings from an ActiveX object to JScript but in C#.

I have an COM control that passes back an array of strings to javascript. It seems like javascript cant understand what it is I am passing back and the array in javascript is always undefined.

Javascript:

try
 {
  keystore.openKeyStore("MY", true, false);
  var fNames = new Array();
  fNames = keystore.getAllFriendlyNames();
  document.getElementById('par').innerHTML = fNames[0];
 }
 catch(err)
 {
  document.getElementById('err').innerHTML = err.description;
 }

That outputs 'undefined' for fNames[0];

C#:

    public object[] getAllFriendlyNames()
    {
        if (!keystoreInitialized)
            throw new Exception("Key store has not been initialized");

        X509Certificate2Collection allCerts = certificateStore.Certificates;

        int storeSize = allCerts.Count;

        if (storeSize == 0)
            throw new Exception("Empty Key Store, could have opened using the wrong keystore name.");

        object[] friendlyNames = new object[storeSize];

        for (int i = 0; i < storeSize; i++)
        {
            string friendlyName = allCerts[i].FriendlyName;

            if (friendlyName == "")
                friendlyName = allCerts[i].Subject;

            friendlyNames[i] = (object) friendlyName;
        }

        return friendlyNames;
  }

I've tried returning both object arrays and string arrays to no avail.

2条回答
该账号已被封号
2楼-- · 2020-02-29 07:01

You can try serializing your data to json and deserializing on the client. jQuery has built in json functions. I've done this with more complex objects, but not with string arrays, though I'd bet that it will work just as easily.

查看更多
看我几分像从前
3楼-- · 2020-02-29 07:28

You can send JavaScript array directly from your activeX method, your function will be:

public ArrayObject getAllFriendlyNames()
{
    //.... the same ...... 
    return Microsoft.JScript.GlobalObject.Array.ConstructArray(friendlyNames);
}

Adding Microsoft.JScript reference to your project.


MSDN: ArrayConstructor.ConstructArray Method

查看更多
登录 后发表回答