我目前正在开发一个用ASP.NET开发的网站。我使用SignalR发布数据库中的实时更改。例如,我有一个包含消息和NewMessageCount
的表。每次NewMessageCount
上升时,用户都会收到通知。但是我的问题是当用户点击通知时它没有减少。例如,如果用户有两个通知并单击Message
选项卡,则会下降到0而不是1,然后是0。
以下是Hub
[HubMethodName("removeNotifications")]
public string RemoveNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("UPDATE Messages SET NewMessageCount=@NewMessageCount", connection))
{
command.Parameters.AddWithValue("@NewMessageCount", totalNewMessages);
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
var reader = command.ExecuteReader();
}
connection.Close();
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
return context.Clients.All.RemoveNotification(totalNewMessages);
}
对于客户端使用的script
,以下是
<script type="text/javascript">
$(function () {
var notifications = $.connection.notificationHub;
notifications.client.recieveNotification = function (totalNewMessages) {
$('#spanNewMessages').text(totalNewMessages);
};
$.connection.hub.start(function () {
notifications.server.sendNotifications();
$('.Message').click(function () {
notifications.server.removeNotifications();
})
});
});
</script>
我可能会犯一个明显的错误,但我似乎无法弄明白。在此先感谢您的所有帮助和支持。
答案 0 :(得分:0)
试试这个:
$(function () {
var notifications = $.connection.notificationHub;
var newMessages;
notifications.client.recieveNotification = function (totalNewMessages) {
newMessages = parseInt(totalNewMessages);
$('#spanNewMessages').text(totalNewMessages);
};
$.connection.hub.start(function () {
notifications.server.sendNotifications();
$('.Message').click(function () {
newMessages--;
notifications.server.removeNotifications(newMessages);
})
});
});
服务器:
[HubMethodName("removeNotifications")]
public string RemoveNotifications(int newMessages)
{
if(newMessages < 0)
{
return context.Clients.All.RecieveNotification(0);
}
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("UPDATE Messages SET NewMessageCount=@NewMessageCount", connection))
{
command.Parameters.AddWithValue("@NewMessageCount", newMessages);
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
var reader = command.ExecuteReader();
}
connection.Close();
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
return context.Clients.All.RecieveNotification(newMessages);
}
答案 1 :(得分:0)
我设法通过简单地将查询实现到以下
来解决这个问题string query = "UPDATE Messages SET NewMessageCount=NewMessageCount-1 WHERE UserName=@UserName AND NewMessageCount > 0";