signalR向特定客户发送通知

时间:2017-12-14 04:47:44

标签: ajax asp.net-mvc signalr

当我将userId传递给存储过程时,我需要刷新页面以获得实时通知。但是当我使用没有任何参数的存储过程时,下面是我的控制器。

using NuNetwork.Hubs;
using NuNetwork.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NuNetwork.Controllers
{
    public class NotificationController : Controller
    {
        // GET: Notification
        public ActionResult Notification()
        {
            return View();
        }
        public ActionResult GetMessages()
        {

            return PartialView("GetMessages", GetAllMessages());
        }


        public IEnumerable<Messages> GetAllMessages()
        {

            string connString =ConfigurationManager.ConnectionStrings["ConNew"].ConnectionString;
            var messages = new List<Messages>();
            using (var connection = new SqlConnection(connString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand("dbo.USPNotificationSelect", connection))
                {

                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@UserId", SqlDbType.Int).Value =Session["UserId"];
                    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
                            { notification = (int)reader["NotificationId"],
                                post = (string)reader["Post"],
                                notificationType = (string)reader["Note"],
                                createdBy =(string)reader["CreatedBy"],
                                viewedBy =(string) reader["ViewedBy"] });
                    }
                }

            }
            return messages;


        }


        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                MessagesHub.SendMessages();
            }
        }
    }
}

,我的中心是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Configuration;

namespace NuNetwork.Hubs
{
    public class MessagesHub : Hub
    {
        private static string constr = ConfigurationManager.ConnectionStrings["ConNew"].ConnectionString;
        public void Hello()
        {
            Clients.All.hello();
        }
        [HubMethodName("sendMessages")]
        public static void SendMessages()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
            context.Clients.All.updateMessages();

        }
    }
}

我的cshtml页面

@{
    Layout = "~/Views/Shared/HomeNavBar.cshtml";
}
<div class="row">
    <div class="col-md-12">
        <div id="messagesTable"></div>
        <div id="text"></div>
    </div>
</div>
@section Scripts{
    <script src="~/Scripts/jquery.signalR-2.2.2.js"></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 () {

            getAllMessages();
        }).fail(function (e) {
            alert(e);
        });
    });


    function getAllMessages()
    {
        var tbl = $('#messagesTable');
        $.ajax({
            url: '/Notification/GetMessages',
            contentType: 'application/html ; charset:utf-8',
            type: 'GET',
            dataType: 'html'
        }).success(function (result) {
            tbl.empty().append(result);
        }).error(function () {

        });
    }

    </script>
}

那么在将userId传递给存储过程时如何在不刷新页面的情况下获得实时通知

0 个答案:

没有答案