【发布时间】:2014-02-12 03:44:24
【问题描述】:
我正在尝试在我的 ASP.NET MVC Web 应用程序中使用 websockets,但我无法实现,所以在这里我尝试在最终用户网页上显示每个数据库更新,而无需刷新.
HTML:
<span id="nbAlertes"></span>
<ul id="listeAlertes"></ul>
Javascript / SignalR / jQuery
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.0.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
<script>
$(function () {
// Declare a proxy to reference the hub.
var alertes = $.connection.AlerteHub;
// Create a function that the hub can call to broadcast messages.
alertes.client.broadcastMessage = function (nbAlertes, listeAlertes) {
// Html encode display name and message.
var nbA = $('<div />').text(nbAlertes).html();
var lstA = $('<div />').text(listeAlertes).html();
// Add the message to the page.
$('#nbAlertes').text(nbA);
lstA.forEach(function(item) {
$('#listeAlerte').append(item.nomPoste);
});
};
});
</script>
类 AlerteHub:
public class AlerteHub : Hub
{
public void GetAll()
{
var nbAlertes = new CalculAlertesUtilitaire().compter();
var listeAlertes = new CalculAlertesUtilitaire().lister(5);
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(nbAlertes, listeAlertes);
}
MonitoringNDataContext _db = new MonitoringNDataContext();
public string compter()
{
var compte = _db.Alertes.ToList().Count();
return (compte == 0) ? "" : compte.ToString();
}
public ICollection<AlerteModel> lister(int nb)
{
return (ICollection<AlerteModel>)_db.Alertes.ToList().Take(nb).ToArray();
}
}
类启动
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
请问我该怎么做呢?
【问题讨论】:
-
如何它不起作用?会爆炸吗?
-
当我更新数据库时,加载的网页没有更新。
-
您在控制台和网络选项卡中看到了什么?
-
需要在客户端声明参数。
-
@SLaks,我已经根据参数更新了我的帖子。
标签: javascript jquery asp.net-mvc websocket signalr