【发布时间】:2019-03-16 17:08:00
【问题描述】:
我有一个按钮,单击该按钮将/应该通知服务器。然后服务器将值保存到数据库中。如果一切顺利,它应该返回true,否则返回false。
我在我的视图中实例化了一个集线器
var signalRhub = $.connection.hubSignalR;
开始连接:
$.connection.hub.start().done(function () {
$("#submitBut").click(function () {
signalRhub.server.cardAdded();
});
});
定义服务器用来返回布尔值的函数:
signalRhub.client.cardAddedRes = function (isSuccess) {
alert("From server: " + isSuccss);
}
我的 Hub 类:
public class HubSignalR : Hub
{
public bool isSuccess = false; <-- Will be set from controller
public void CardAdded()
{
Clients.Caller.CardAddedRes(isSuccess); <-- Notice the isSuccess
}
}
我的问题是 isSuccess 值来自我的控制器,它与模型/数据库交互。 所以我得到了错误:
Using a Hub instance not created by the HubPipeline is unsupported.
我尝试使用:GlobalHost.ConnectionManager.GetHubContext<HubSignalR>()
但我不能让它工作。
这是我控制器中的相关代码:
private HubSignalR signalR = new HubSignalR(); <-- Field variable
[HttpPost]
public ActionResult AttachCard(Card model, int MemberID)
{
var hub = GlobalHost.ConnectionManager.GetHubContext<HubSignalR>();
...
//We saved to the database, so we call the client function with bool = true
hub.Clients.All.CardAdded(true); <-- Actually I want to send to one client, NOT ALL
//Something like hub.Clients.Caller.CardAdded();
}
我不得不在 HubSignalR 类中创建 isSuccess 字段,因为我需要将其作为参数从我的控制器返回。但是当按钮被点击时,这个值还没有被设置(我认为)。
我可以从调试器中看到,我确实达到了:signalRhub.server.cardAdded();
但是服务器从不响应,所以我没有达到这个功能:
signalRhub.client.cardAddedRes = function (isSuccess) {
alert("From server: " + isSuccss);
}
我并没有真正从我的控制器调用CardAdded() 方法,就像GlobalHost.ConnectionManager.GetHubContext 一样。但是你可以看到
如果您有比我尝试做的更好的解决方案,请告诉我。我对 SignalR 很陌生,对 ASP.net MVC 很陌生
【问题讨论】:
标签: c# asp.net-mvc-4 asp.net-mvc-5 signalr