Search code examples
javascriptjquerysignalrsignalr-hub

Passing an array to server with signalR


How do I pass an array of string in javascript to the server with SignalR?

I have an array in javascript and would like to this to a function to a Hub

var selected = new Array();
$('#checkboxes input:checked').each(function () {
    selected.push($("input").attr('name'));
});

What type of parameter should the function take?


Solution

  • The hub function can take an array of strings, a list of strings etc.

    Here's an example hub:

    public class myHub : Hub
    {
        public void receiveList(List<String> mylist) 
        {
            mylist.Add("z");
            Caller.returnList(mylist);
        }
    }
    

    Here's an example JS piece to work with the hub:

    var myHub = $.connection.myHub,
        myArray = ['a','b','c'];
    
    myHub.client.returnList = function(val) {
        alert(val); // Should echo an array of 'a', 'b', 'c', 'z'
    }
    
    $.connection.hub.start(function() {
        myHub.server.receiveList(myArray);
    });