我正在使用MVC 5,我有这样的集线器类:
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);
}
}
我在我的网页上有这个代码:
$(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 () {
});
});
我还在项目的启动中添加了MapHub。我的问题是:
在服务器端,我想在创建新事件后立即更新网页。如何按需触发广播方法?我不能只创建集线器的实例并调用方法。
答案 0 :(得分:1)
您可以通过GlobalHost
访问中心上下文,例如:
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.broadcastEvent(...)