Member 11933660 Ответов: 0

Как отобразить обновленные записи на странице просмотра с помощью signalr?


Using SignalR need display updated records without refresh page i tried using signalR not working depenedncy on change event please help on this


Что я уже пробовал:

using SignalRDbUpdates.Hubs;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace SignalRDbUpdates.Models
{
    public static class MessagesRepository
    {
        public static bool startUp = true;
        public static bool subscribe = true;
        public static SqlDependency dependency = null;
        //readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        public static IEnumerable<Messages> GetAllMessages()
        {
            var messages = new List<Messages>();
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
            {
                connection.Open();
                using (var command = new SqlCommand(@"SELECT [JobId], [JobDesrciption], [JobName], getdate() as Date FROM [dbo].[ScheduleJobs]", connection))
                {
                    command.Notification = null;

                    //var dependency = new SqlDependency(command);
                    ////SqlDependency.Stop(_connString);
                    ////SqlDependency.Start(_connString);
                    //dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                    //SqlDependency.Stop(_connString);
                    //SqlDependency.Start(_connString);
                    if (connection.State == ConnectionState.Closed)
                        connection.Open();
                    if (subscribe)
                    {
                        // Create and bind the SqlDependency object
                        // to the command object.
                        dependency = new SqlDependency(command);
                        dependency.OnChange -= new OnChangeEventHandler(dependency_OnChange);
                        dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                        subscribe = false;
                    }
                    var reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        messages.Add(item: new Messages { MessageID = (int)reader["JobId"], Message = (string)reader["JobDesrciption"], EmptyMessage =  reader["JobName"] != DBNull.Value ? (string) reader["JobName"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
                    }
                }
              
            }
            return messages;
           
            
        }

        private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            //if (e.Type.ToString() == "subscribe")
            //{
            //    MessagesHub.SendMessages();
            //}
            if (e.Type == SqlNotificationType.Change &&
                (e.Info == SqlNotificationInfo.Insert ||
                 e.Info == SqlNotificationInfo.Delete ||
                 e.Info == SqlNotificationInfo.Update)
              )
            {
                // Remove the handler, since it is only good for a single notification.
                SqlDependency dependency = (SqlDependency)sender;
                dependency.OnChange -= dependency_OnChange;
                MessagesHub.SendMessages();
                subscribe = true;
            }
        }
    }
}




@{
    ViewBag.Title = "Home Page";
}



<div class="row">
    <div class="col-md-12">
       <div id="messagesTable"></div>
    </div>
</div>

@section Scripts{
<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',
            cache: false,
            contentType: 'application/html ; charset:utf-8',
            type: 'GET',
            dataType: 'html'
        }).success(function (result) {
            tbl.empty().append(result);
        }).error(function () {
            
        });

    }
</script>

}




using SignalRDbUpdates.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SignalRDbUpdates.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        [OutputCache(Duration = 0)]
        public ActionResult GetMessages()
        {
           // MessagesRepository _messageRepository = new MessagesRepository();
            return PartialView("_MessagesList", MessagesRepository.GetAllMessages());
        }
    }
}



using SignalRDbUpdates.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SignalRDbUpdates.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        [OutputCache(Duration = 0)]
        public ActionResult GetMessages()
        {
           // MessagesRepository _messageRepository = new MessagesRepository();
            return PartialView("_MessagesList", MessagesRepository.GetAllMessages());
        }
    }
}

0 Ответов