Pouyan Pouyan - 1 month ago 21
C# Question

signalR updating client web page with new items

I'm using MVC 5 and I have my hub class like this :

public class EventHub : Hub
{
public void broadcastEvent(string userId = "",
string source = "",
string application = "",
string type = "",
string importance = "",
string message = "",
string timeStamp = "",
string stackTrace = "",
string exceptionMessage = "",
string innerExceptionMessage = "",
string objectContext = "",
string serverName = "",
string actionResult = "")
{
Clients.All.broadcastEvent(userId, source, application, type, importance, message, timeStamp, stackTrace, exceptionMessage, innerExceptionMessage, objectContext, serverName);
}
}


and I have this Code in my web page:

$(function () {
var app = $.connection.eventHub;
app.client.broadcastEvent = function (userId,
source,
application,
type,
importance,
message,
timeStamp,
stackTrace,
exceptionMessage,
innerExceptionMessage,
objectContext,
serverName,
actionResult) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('.row').append("div>asfdasdf</div>");
};

$.connection.hub.start().done(function () {
});
});


And I also added the MapHub in the Startup of my project. My Question is:

On the server side I want to update the webpage as soon as new event has been created. How can I trigger the broadcast method on demand ? I can't just create an instance of the hub and call the method.

Answer

You can access hub context via GlobalHost for instance:

var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.broadcastEvent(...)