I am trying to broadcast a message to all clients by using SignalR in a mvc application. The problem I am encountering is that when I use this code
var context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
the context has no client, so the message will not be broadcasted. Here below is a simplified version of the code that I am using. I am missing something ? Thanks
The view:
@using System.Web.UI.WebControls
@using MyApp.Models
@model MyApp.Models.MyModel
<form class="float_left" method="post" id="form" name="form">
<fieldset>
Username: <br/>
@Html.TextBoxFor(m => m.Username, new { Value = Model.Username })
<br/><br/>
<input id="btnButton" type="button" value="Subscribe"/>
<br/><br/>
<div id="notificationContainer"></div>
</fieldset>
</form>
@section scripts {
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
$(function () {
var notification = $.connection.notificationHub;
notification.client.addNewMessageToPage = function (message) {
$('#notificationContainer').append('<strong>' + message + '</strong>');
};
$.connection.hub.start();
});
$("#btnButton").click(function () {
$.ajax({
url: "/Home/Subscribe",
data: $('#form').serialize(),
type: "POST"
});
});
</script>
}
The Hub:
namespace MyApp.Hubs
{
public class NotificationHub : Hub
{
public void Send(string message)
{
Clients.All.addNewMessageToPage(message);
}
}
}
The Controller:
namespace MyApp.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public void Subscribe()
{
var message = "" // get message...
var context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
context.Clients.All.Send(message);
}
}
}
You have the concepts a little mixed up.
The thing is that you can't call a hub method from another place in the back-end, so you can't make a call to he Send
hub mehod but from anywhere but the connected client(in your case the website).
When you do Context.Clients.doSomething()
you actually call the client part of SignalR
and tell it to execute the JavaScript method doSomething()
if it exists.
So your call from the controller should be context.Clients.All.addNewMessageToPage(message);
Hope this helps. Best of luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With