简体   繁体   English

如何将对象数组从C#发送到JavaScript?

[英]How to send an object array from c# to javascript?

Im trying to send an array that contains some objects via connection made in SignalR, the connection is not a problem, everything works fine. 我试图通过SignalR中的连接发送一个包含一些对象的数组,该连接不是问题,一切正常。 When the data arrives to the view it is no longer the array i need to use. 当数据到达视图时,它不再是我需要使用的数组。 This is the class: 这是课程:

public class Empresa
    {
        public string nombre { get; set; }
        public int vidID { get; set; }
        public string img64 { get; set; }
        public string color { get; set; }

    }

At the end the object will be something like this: 最后,对象将是这样的:

样品

The object is send to the view and this is the output: 该对象被发送到视图,这是输出:

产量

I have already tried with JsonConvert.SerializeObject as i found on other threads, yet it doesnt seems to work. 我已经尝试过在其他线程上找到JsonConvert.SerializeObject ,但它似乎不起作用。 I tried to convert the data send with this jQuery.parseJSON(data) (Left) and with this JSON.parse(data) (Right); 我试图转换使用此jQuery.parseJSON(data) (左)和此JSON.parse(data) (右) JSON.parse(data) it throws an error on both cases as seen in the picture below. 如下图所示,这两种情况都会引发错误。

错误,左= jQuery.parseJSON右= JSON.parse

I'm not sure if it is that way because the object sended is made this way: 我不确定是不是这样,因为发送的对象是这样制作的:

private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();

var data = new List<Empresa>
{
   new Empresa{nombre ="Globex Corp",color="red",vidId=1, img="data:image/jpeg;base64,blabla" },
   new Empresa{nombre ="AM",color="blue",vidId=2, img="data:image/jpeg;base64,blabla" }
}
for(int i = 0; i<=6; i++)
{
    _ar1.TryAdd(data[i].vidID, data[i]);
}

This is inside other function but it is the next one that involves the data send. 这是在其他功能中,但它是涉及数据发送的下一个功能。

public IEnumerable<Empresa> GetArreglo()
        {
           return _ar1;
        }

So far im not sure what could be wrong or if i need to aproach a different solution. 到目前为止,我不确定可能有什么问题,或者我是否需要提出其他解决方案。 If any more info is needed ill post it. 如果需要更多信息,请张贴。 And even it is obvious im a newby still learning on this. 甚至很明显,我仍然在学习新知识。

EDIT: 编辑:

This is all the code involved: 这是所有涉及的代码:

// This is the JS
<script>

        var ubi = '@ViewBag.ubicacion';
        console.log("Ubicación: " + ubi);
        var conex = $.connection.channel;
        var $marco = $('#marco');
        var $imagen = $('#imagen');
        var $empresa = $('#empresa');

        function empezar() {

            var min;
            var max;
            var pos;
            var arreglo = new Array;



            function init() {

                conex.server.createGroup(ubi);
                console.log("Entro al canal");
                arreglo = conex.server.getArreglo(ubi);
                //pos = arreglo.split('|');
                //a.split is not a function
                console.log(arreglo);
                //console.log(pos);
                setInterval(update, 6000);

            }

            function update() {


            }

            $.connection.hub.start().done(init);
        }

        window.onload = function() { empezar(); }
    </script>

    //It gets the conection to the HUB:

    [HubName("channel")]
    public class CanalHub : Hub
    {
        private readonly Canal _canal;

        public CanalHub() : this(Canal.Instance) { }

        public CanalHub(Canal canal)
        {
            _canal = canal;
        }



        public string[] GetArreglo(string ubi)
        {
            string[] array = _canal.GetArreglo(ubi);
            return array;
            //it is now a string[] because i wanted to
            //try creating the obj with .split('|')
        }


// And finally this is the last part involved:

 public class Canal
    {

        private static Random random = new Random();
        private volatile List<Canales> listaCan = new List<Canales>();
        private readonly static Lazy<Canal> _instance = new Lazy<Canal>(() => new Canal(GlobalHost.ConnectionManager.GetHubContext<CanalHub>().Clients));
        private readonly ConcurrentDictionary<int, Empresa> _datos = new ConcurrentDictionary<int, Empresa>();
        private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();

        private Canal(IHubConnectionContext<dynamic> clients)
        {
            Clients = clients;

            //Create the sample objects for the class
            var datos = new List<Empresa>
            {
                new Empresa{nombre="Globex Corp", color="#A87F3D", vidID=1, img="balbal" },
                new Empresa{nombre="AM", color="#535E89", vidID=2, img="balba" },
                new Empresa{nombre="Frutijugos", color="#92191A", vidID=3, img="askldj" }
    };


            for (int i = 0; i <=6 ; i++)
            {
                _ar1.TryAdd(datos[i].vidID, datos[i]);
            }
            for (int i = 7; i <= 13; i++)
            {
                _ar2.TryAdd(datos[i].vidID, datos[i]);
            }
            for (int i = 14; i <= 20; i++)
            {
                _ar3.TryAdd(datos[i].vidID, datos[i]);
            }
            //sort them on 3 different arrays
        }

        private IHubConnectionContext<dynamic> Clients { get; set; }

        public static Canal Instance
        {
            get { return _instance.Value; }
        }


        public string[] GetArreglo(string ubi)
        {
            string[] array = new string[7];
            int i = 0;

            if (ubi == "Campanario")
            {
                foreach (var item in _ar1)
                {
                    array[i] += item.Value.nombre + "|";
                    array[i] += item.Value.color + "|";
                    array[i] += item.Value.img + "|";
                    array[i] += item.Value.vidID + "|";
                    i++;
                }

                return array;
            }
            //sort the array values and add them to the array

            else return null;          
        }

It appears that your javascript promise is not set up correctly. 看来您的JavaScript承诺未正确设置。 The object in the view is the promise object and not the object returned. 视图中的对象是Promise对象,而不是返回的对象。 You are going to need to set up the promise correctly. 您将需要正确设置承诺。 deferred promise 延期承诺

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM