I've been trying to run several procedural code on server with parameter that i put on form and execute with MVC Controller. I want every step (method / function) on controller that have been called will update information to the client Web real-time.
I've been trying to use SignalR to update realtime push notification / information to client, its work with client trigger but when i trying to call hub from controller it doest work.
here is my Controller Code :
[HttpPost]
public string data (Models.ExModel data)
{
var hub = GlobalHost.ConnectionManager.GetHubContext<Hubs.MyHub1>();
//Execute Code
//send to client
hub.Clients.All.Message(data.apaAja);
return "success";
}
here is my client code :
<h2>Index</h2>
@Ajax.BeginForm("data", "Home", FormMethod.Post, null) {
<div class="input-group">
<span>Apa Aja</span>
@Html.EditorFor(model => model.apaAja, new { htmlhtmlAttributes = new { @id = "apaAja" } })
</div>
<div class="input-group">
<span> Boleh </span>
@Html.EditorFor(model => model.boleh, new { htmlhtmlAttributes = new { @id = "boleh" } })
</div>
<button id="subm" type="submit">Submit</button>
<div id="container">
</div>
@section scripts{
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
$(document).ready(function () {
var c = $.connection.myHub1;
c.client.messageSend = function (message) {
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#container').append('<li> < strong >' + 'Info Message : ' +
'</strong >: ' + encodedMsg + '</li >');
};
$.connection.hub.start();
});
</script>
and here is my Hub Class :
namespace SignalR1.Hubs
{
public class MyHub1 : Hub
{
public void Message(string message)
{
Clients.All.messageSend(message);
}
}
}
You have a client-side callback called messageSend, then in your hub you rightly have Clients.All.messageSend, however when you use the GlobalHost.ConnectionManager.GetHubContext you are accessing the hub context not the hub class itself.
So change it to:
var hub = GlobalHost.ConnectionManager.GetHubContext<Hubs.MyHub1>();
//you don't actually have access to the MyHub1 class at this point
// instead of
// hub.Clients.All.Message(data.apaAja);
// you need
hub.Clients.All.messageSend(data.apaAja);
In fact, the hub class method becomes slightly redundant when using this mechanism. I normally use the hub class for managing connections and clients using the overrides for onconnected etc...