Currently, I am diving into the world of SignalR and attempting to create a basic message notification system. However, despite my limited understanding of SignalR, I am unable to display the messages after submission.
I have researched multiple blogs on this topic and it seems that the key is to have a VOID method that takes a string value and then sends it back by attaching it to the Clients context. However, I am encountering issues as the onReceiveNotification() function is always undefined in the JS debugger.
Am I overlooking something?
notificationhub.cs
[HubName("notificationHub")]
public class NotificationHub : Hub
{
public override System.Threading.Tasks.Task OnConnected()
{
return base.OnConnected();
}
public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
{
return base.OnDisconnected(stopCalled);
}
public override System.Threading.Tasks.Task OnReconnected()
{
return base.OnReconnected();
}
[HubMethodName("sendNotifications")]
public void SendNotifications(string message)
{
Clients.All.onRecieveNotification(string.Format("{0} {1}", message, DateTime.Now.ToString()));
}
}
message.html page
<div>
<input type="text" id="messageinput" />
<button id="notifybutton">Send Message</button>
</div>
<script src="Scripts/jquery-2.1.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
jQuery(document).ready(function ($)
{
var $hub = $.connection.notificationHub;
$.connection.hub.start();
$(document).on("click", "#notifybutton", {}, function (e)
{
e.preventDefault();
var $message = $("#messageinput").val();
$hub.server.sendNotifications($message);
});
});
</script>
display.html
<div>
<ul id="messages"></ul>
</div>
<script src="Scripts/jquery-2.1.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
jQuery(document).ready(function ($)
{
var $hub = $.connection.notificationHub;
$hub.onRecieveNotification = function (message)
{
$("#message").append($("<li></li>", { text: message }));
}
$.connection.hub.start();
});
</script>