I'm trying to implement SignalR into a simple MVC 5 project. I've worked through this tutorial and it works, but I'm now trying to call a hub method from a separate controller.
I have a view called Generate.cshtml, with this markup and Javascript:
<script type="text/javascript">
$(function() {
var myHub = $.connection.ContosoChatHub;
myHub.client.writeMessageToScreen = function(message) {
$('#messages').append(message);
};
});
</script>
<input type="text" id="msg" />
<input type="button" id="broadcast" value="broadcast" />
<ul id="messages" class="round">
</ul>
the hub class is
[HubName("ContosoChatHub")]
public class ContosoChatHub : Hub
{
public void NewContosoChatMessage(string message)
{
Clients.All.NewMessage(message);
}
}
and then in my controller, I want to call the writeMessageToScreen method - either calling it directly, or via the hub class.
I've read that I can call the Javascript method directly
public ActionResult Generate()
{
var context = GlobalHost.ConnectionManager.GetHubContext<ContosoChatHub>();
context.Clients.All.writeMessageToScreen("Test");
return View();
}
But this isn't working and nothing is written to screen.. It isn't throwing any errors either, it just isn't doing.. anything.
Does anyone have any ideas what's going on? Is there a better way to call Hub methods from a Controller?
$.connection.hub.start(). Is there one? SignalR Hubs API Guide - JavaScript Client