我正在尝试使用 ASP.NET MVC 4 创建类似 Facebook 的通知模块。
我的数据库中只有几个表。
一旦有人更改(插入/更新/删除)数据库中这些表的行,我就可以在我的应用程序前端将其显示为通知
只是想知道解决这个问题的最佳方法,非常感谢可以提供任何建议或资源
谢谢!
最佳答案
您可以使用SignalR这是一个用于开发需要实时通信的应用程序的库。在此类应用程序中,一旦服务器上生成数据或服务器上发生一些有趣的事件,客户端就需要使用最新数据进行更新。实现此功能的传统方法是定期对服务器进行 Ajax 调用。然而,这种方法有其自身的缺陷。另一种方法是使用 HTML5 Web Sockets 或服务器发送事件 (SSE) 来执行实时通信。然而,这两种技术仅适用于支持 HTML5 的浏览器。如果目标浏览器支持 HTML5 Web Sockets,SignalR 就会使用它们,否则它会回退到其他技术。
创建通知系统。如果您使用 ASP.NET WebForms,请向项目添加一个新的 SignalR Hub 类,如下所示:
namespace SignalRDemo
{
public class MyHub1 : Hub
{
//call method like SendNotifications when your database is changed
public void SendNotifications(string message)
{
Clients.All.receiveNotification(message);
}
}
}
接下来,将 Global.asax 文件添加到您的 Web 应用程序,并在 Application_Start 事件处理程序中编写以下代码。
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHubs();
}
此外,您还可以在 Scripts 文件夹下找到某些脚本文件。
现在,向项目添加一个 Web 表单并将其命名为 AdminForm.aspx。在 Web 表单中添加以下标记:
<!DOCTYPE html>
<html>
<head>
<title>Admin Form Sending Notifications</title>
<script src="/Scripts/jquery-1.8.2.min.js" ></script>
<script src="/Scripts/jquery.signalR-1.0.0.js"></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var proxy = $.connection.notificationHub;
$("#button1").click(function () {
proxy.server.sendNotifications($("#text1").val());
});
$.connection.hub.start();
});
</script>
</head>
<body>
<input id="text1" type="text" />
<input id="button1" type="button" value="Send" />
</body>
</html>
AdminForm.aspx 引用头部部分中的 SignalR 脚本文件。请注意以粗体字母标记的代码。首先声明一个名为 proxy 的变量来保存对远程集线器类 (NotificationHub) 的代理的引用。确保客户端代码在命名约定中使用驼峰式大小写。例如,NotificationHub在客户端代码中称为notificationHub。
接下来,按钮的单击事件处理程序将连接到一个函数。客户端事件处理程序调用代理对象上的 sendNotifications() 方法,并传递在文本框中输入的通知消息(请参阅前面的图以了解管理表单的外观)。
最后调用集线器的start()方法来启动连接。
将另一个 Web 表单添加到项目中,并将其命名为 ClientForm.aspx。在 Web 表单中键入以下标记:
<!DOCTYPE html>
<html>
<head>
<title>Client Form Receiving Notifications</title>
<script src="/Scripts/jquery-1.8.2.min.js" ></script>
<script src="/Scripts/jquery.signalR-1.0.0.js"></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var proxy = $.connection.notificationHub;
proxy.client.receiveNotification = function (message) {
$("#container").html(message);
$("#container").slideDown(2000);
setTimeout('$("#container").slideUp(2000);', 5000);
};
$.connection.hub.start();
});
</script>
</head>
<body>
<div class="notificationBalloon" id="container">
</div>
</body>
</html>
现在,从管理员发送的通知将像这样显示给所有客户端。
要使用 SignalR 和 SQL 依赖项显示来自 SQL Server 的实时更新,请按照下列步骤操作:
第 1 步:在数据库上启用 Service Broker
以下是需要启用Service Broker的查询
ALTER DATABASE BlogDemos SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ;
第 2 步:启用 SQL 依赖项
//Start SqlDependency with application initialization
SqlDependency.Start(connString);
第3步:创建集线器类
public class MessagesHub : Hub
{
private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
public void Hello()
{
Clients.All.hello();
}
[HubMethodName("sendMessages")]
public static void SendMessages()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
context.Clients.All.updateMessages();
}
}
第 4 步:从存储库获取数据
创建MessagesRepository以在数据更新时从数据库获取消息。
public class MessagesRepository
{
readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
public IEnumerable<Messages> GetAllMessages()
{
var messages = new List<Messages>();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(@"SELECT [MessageID], [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
{
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
messages.Add(item: new Messages { MessageID = (int)reader["MessageID"], Message = (string)reader["Message"], EmptyMessage = reader["EmptyMessage"] != DBNull.Value ? (string) reader["EmptyMessage"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
}
}
}
return messages;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
MessagesHub.SendMessages();
}
}
}
第5步:在启动类中注册SignalR
app.MapSignalR();
第6步:然后使用该方法在您的 View 中显示实时
<script src="/Scripts/jquery.signalR-2.1.1.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.messagesHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getAllMessages()
};
// Start the connection.
$.connection.hub.start().done(function () {
alert("connection started")
getAllMessages();
}).fail(function (e) {
alert(e);
});
});
function getAllMessages()
{
var tbl = $('#messagesTable');
$.ajax({
url: '/home/GetMessages',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
tbl.empty().append(result);
}).error(function () {
});
}
</script>
希望这有帮助:)
关于jquery - 为数据库更改创建像 Facebook 一样的实时通知模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28017993/