kez*_*kez 4 ajax asp.net-mvc jquery asp.net-mvc-4 signalr
我正在尝试使用ASP.NET MVC 4创建像Facebook这样的通知模块.
我的数据库中有几张表.
一旦有人在数据库中更改(插入/更新/删除)这些表的行,我就能在应用程序前端将其显示为通知
只是想知道最好的方法来解决这个问题,高度赞赏可以给出任何建议或资源
谢谢!
Ami*_*nul 10
您可以使用SignalR作为开发需要实时通信的应用程序的库.在这样的应用程序中,只要在服务器上生成数据或在服务器上发生一些有趣的事件,客户端就需要使用最新数据进行更新.实现此功能的传统方法是定期对服务器进行Ajax调用.然而,这种方法有其自身的缺陷.另一种方法是使用HTML5 Web套接字或服务器发送事件(SSE)来执行实时通信.但是,这两种技术都只适用于支持HTML5的浏览器.如果目标浏览器支持,SignalR使用HTML5 Web套接字,否则它将回退到其他技术.
创建通知系统.如果您使用的是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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
接下来,将Global.asax文件添加到Web应用程序,并在Application_Start事件处理程序中编写以下代码.
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHubs();
}
Run Code Online (Sandbox Code Playgroud)
此外,您将在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>
Run Code Online (Sandbox Code Playgroud)
AdminForm.aspx引用head部分中的SignalR脚本文件.请注意以粗体字母标记的代码.首先,声明一个名为proxy的变量来保存对远程集线器类(NotificationHub)的代理的引用.确保客户端代码在命名约定中使用camel大小写.例如,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>
Run Code Online (Sandbox Code Playgroud)
现在,管理员发送的通知将显示给所有这样的客户端.
要使用SignalR和SQL依赖关系从SQL Server显示实时更新,请按照下列步骤操作:
步骤1:在数据库上启用Service Broker
以下是需要启用服务代理的查询
ALTER DATABASE BlogDemos SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ;
Run Code Online (Sandbox Code Playgroud)
第2步:启用SQL依赖项
//Start SqlDependency with application initialization
SqlDependency.Start(connString);
Run Code Online (Sandbox Code Playgroud)
第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();
}
}
Run Code Online (Sandbox Code Playgroud)
第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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
步骤5:在启动阶段注册SignalR
app.MapSignalR();
Run Code Online (Sandbox Code Playgroud)
第6步:然后使用该方法在您的视图中显示实时
<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>
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助 :)
归档时间: |
|
查看次数: |
7472 次 |
最近记录: |