我想在我的ASP.NET MVC Web應用中使用websockets,但我無法實現,所以在這裏我試圖在最終用戶網頁上顯示每個數據庫更新任何需要刷新。使用SignalR實現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
當我更新數據庫時,沒有更新到加載的網頁。 –
你在控制檯和網絡標籤中看到了什麼? – SLaks