Question

I have been reading this article from the documentation:

http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-getting-started-with-signalr-20-and-mvc-5

It says, I can send a message from the client to the server like so:

$.connection.hub.start().done(function () {
    $('#sendmessage').click(function () {
        // Call the Send method on the hub. 
        chat.server.send($('#displayname').val(), $('#message').val());
        // Clear text box and reset focus for next comment. 
        $('#message').val('').focus();
    });
});

But, how can I send a message from my server to the client?

I was first following this tutorial http://www.codemag.com/Article/1210071 which explained that I need simply to do this:

SendMessage("Index action invoked.");

With SendMessage() defined as:

private void SendMessage(string message)
{
    GlobalHost.ConnectionManager.GetHubContext<NotificationHub>().Clients.All.sendMessage(message);
}

But, this doesn't work. On my client side, my error is:

Object # has no method 'activate'

The client side code that I am using is:

$.connection.hub.start(function () {
    notificationHub.activate(function (response) {
        /*
        $("#target")
         .find('ul')
         .append($("<li></li>").html(response));
         */
        console.log(response);
    });
});

So, the question is, how can I send a simple message from my server to the client?

Can someone show me a complete example of how to do this? I have seen the stock ticker example from the documentation, but it is kind of hard to understand/ apply.

Was it helpful?

Solution

From what I understand you are calling a function on client called sendMessage here

private void SendMessage(string message)
{
    GlobalHost.ConnectionManager.GetHubContext<NotificationHub>().Clients.All.sendMessage(message);
}

However, I don't see a definition for this function on client side. Instead you have defined a function called activate(). Additionally, from my working code, I have defined the client side functions like this.

    var hub = $.connection.notificationHub;
    hub.client.sendMessage= function (data) {
//some logic here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top