Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call signalr from another controller

I have a ChatHub sending message to the client:

public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        Clients.All.addNewMessageToPage(name, message);
    }
}

How can I call the Send function to broadcast the message to all client from another controller?

I have tried this:

[HttpPost]
public void Post(Chat chat)
{
    var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
    hubContext.Clients.All.Send(chat.Name, chat.Message);
}
like image 509
Alvin Avatar asked Jan 10 '14 13:01

Alvin


1 Answers

You need to call addNewMessageToPage in your Post action method.

var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
hubContext.Clients.All.addNewMessageToPage(chat.Name, chat.Message);

Then in your JS file:

var chatHub = $.connection.chatHub;

chatHub.client.addNewMessageToPage= function (name, message) {
    //Add name and message to the page here
};
$.connection.hub.start();
like image 69
Lin Avatar answered Sep 21 '22 01:09

Lin