Jquery 为数据库更改创建实时通知模块,如Facebook

Jquery 为数据库更改创建实时通知模块,如Facebook,jquery,ajax,asp.net-mvc,asp.net-mvc-4,signalr,Jquery,Ajax,Asp.net Mvc,Asp.net Mvc 4,Signalr,我正在尝试使用ASP.NETMVC4创建类似Facebook的通知模块 我的数据库中几乎没有表 一旦有人更改(插入/更新/删除)数据库中这些表的行,我就能够在我的应用程序前端将其显示为通知 只是想知道解决这个问题的最佳方法,非常感谢您能提供任何建议或资源 谢谢大家! 您可以使用SqlDependency+signar来完成这项工作 点击此链接: SqlDependency: 信号器:您可以使用它来开发需要实时通信的应用程序。在此类应用程序中,一旦服务器上生成数据或服务器上发生一些有趣的事件,客户

我正在尝试使用ASP.NETMVC4创建类似Facebook的通知模块

我的数据库中几乎没有表

一旦有人更改(插入/更新/删除)数据库中这些表的行,我就能够在我的应用程序前端将其显示为通知

只是想知道解决这个问题的最佳方法,非常感谢您能提供任何建议或资源


谢谢大家!

您可以使用SqlDependency+signar来完成这项工作

点击此链接:
SqlDependency:

信号器:

您可以使用它来开发需要实时通信的应用程序。在此类应用程序中,一旦服务器上生成数据或服务器上发生一些有趣的事件,客户端就需要使用最新数据进行更新。实现此功能的传统方法是定期对服务器进行Ajax调用。然而,这种方法也有其自身的缺陷。另一种方法是使用HTML5Web套接字或服务器发送事件(SSE)来执行实时通信。然而,这两种技术都只能在支持HTML5的浏览器上工作。如果目标浏览器支持HTML5WebSockets,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应用程序中,并在应用程序启动事件处理程序中编写以下代码

protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapHubs();
}
此外,您将在“脚本”文件夹下找到某些脚本文件

现在,向项目中添加一个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>
<!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>
步骤2:启用SQL依赖关系

    //Start SqlDependency with application initialization
     SqlDependency.Start(connString);
步骤3:创建hub类

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();
        }


    }
第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>

$(函数(){
//声明代理以引用中心。
var通知=$.connection.messagesHub;
//调试器;
//创建一个中心可以调用以广播消息的函数。
notifications.client.updateMessages=函数(){
getAllMessages()
};
//启动连接。
$.connection.hub.start().done(函数(){
警报(“连接已启动”)
getAllMessages();
}).失败(功能(e){
警报(e);
});
});
函数getAllMessages()
{
var-tbl=$('#messagesTable');
$.ajax({
url:“/home/GetMessages”,
contentType:'应用程序/html;字符集:utf-8',
键入:“GET”,
数据类型:“html”
}).成功(功能(结果){
tbl.empty().append(结果);
}).错误(函数(){
});
}

希望这有帮助:)

你可能想看看耶!我已经将该库添加到我的项目中,因为我也遵循了本教程,但在本教程中,当我们更改表行时,它不会显示任何通知。然后,您需要发布您尝试过的代码并解释问题。以下是信号器示例代码的逐步实现,如果您已经实现,但它不起作用,请在此处发布您的代码。@MokshShah此链接不起作用,非常感谢您的指导,但在本例中,您似乎没有使用任何数据库,如果我的解释错误,请更正。。谢谢
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();
            }
        }
    }
app.MapSignalR();
<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>