Pass Array From C# COM object to JavaScript?

好久不见. 提交于 2019-11-29 22:55:41

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/3354565/pass-array-from-c-sharp-com-object-to-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!