Based on various resources the signalr
code should be working, but I can't make it to send notifications from the server to client. Here is html/javascript part:
<script src="/Scripts/jquery-1.6.4.min.js"></script>
<script src="/Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="/signalr/js"></script>
<script type="text/javascript">
$(function () {
var cHub = $.connection.cHub;
$.connection.hub.logging = true;
cHub.client.sendMessage = function (content) {
$("#container-hub").append($("<p />").html(content));
};
$.connection.hub.start().done(function() {
$('[id$=bGo]').click(
function() {
cHub.server.send('Sync process started');
});
});
});
</script>
<div id="container-hub" style="background: red; height: 100px; width: 100%;"></div>
Hub.cs class:
using Microsoft.AspNet.SignalR;
namespace CMS.Objects
{
public class CHub : Hub
{
public void Send(string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.sendMessage(message);
}
}
}
Startup.cs class:
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(CMS.CStartup))]
namespace CMS
{
public class CStartup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
And here is how I am calling the method sendMessage
method:
private void ShowMessage(string message)
{
var clients = GlobalHost.ConnectionManager.GetHubContext<CHub>().Clients;
clients.All.sendMessage(message);
}
When the button bGo
is clicked the message is getting appended to the container-hub
div, but nothing when I call sendMessage
method.
EDIT
Some additional findings; when I call sendMessage
from within the OnConnected
method it works:
public override Task OnConnected()
{
Clients.All.sendMessage("Connection Initialised");
return base.OnConnected();
}
After spending some decent time to investigate the problem I have finally found the solution. Not 100% sure, but I think the problem was with using the UpdatePanel
on the page. Wrapped signalR
javascript code to Sys.Application.add_load
instead of using jQuery's $(function () {
and it started working.
The reason I mentioned that I am not 100% sure is that the UpdatePanel
with the ScriptManager
has been removed multiple times giving no results before posting the question.