无法使用SignalR实时更新带有数据库通知的网页

时间:2015-01-06 20:22:35

标签: javascript html5 asp.net-mvc-4 signalr

我正在开发一个使用Asp.Net MVC开发的Web应用程序,我在该页面上有一个页面,只要数据在数据库上被修改,数据就会实时更新。我有一些在线资源,并试图实现此功能,但它导致网页上的大量无效数据。

我正在使用SQL依赖和SignalR来实现如下

Global.asax中,我有以下

protected void Application_Start()
{
    SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString); 
}
protected void Application_End()
{
    SqlDependency.Stop(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString); 
}

在模型部分我有以下类

public class JobInfo 
{
    public int JobID { get; set; }
    public string Name { get; set; }
    public DateTime LastExecutionDate { get; set; }
    public string Status { get; set; }
}

 public class JobInfoRepository 
 {
    public IEnumerable<JobInfo> GetData()
    {
        using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand(@"SELECT [JobID],[Name],[LastExecutionDate],[Status]
               FROM [dbo].[JobInfo]", connection))
            {
                // Make sure the command object does not already have
                // a notification object associated with it.
                command.Notification = null;

                SqlDependency dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                if (connection.State == ConnectionState.Closed)
                    connection.Open();

                using (var reader = command.ExecuteReader())
                    return reader.Cast<IDataRecord>()
                        .Select(x => new JobInfo(){ 
                            JobID = x.GetInt32(0), 
                            Name = x.GetString(1), 
                            LastExecutionDate = x.GetDateTime(2),  
                            Status  = x.GetString(3) }).ToList();         
            }
        }        
    }
    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {            
        JobHub.Show(); 
    }
}

我创建了一个SignalR Hub类,其中包含上述类中使用的Show()函数

using Microsoft.AspNet.SignalR.Hubs;

public class JobHub : Hub
{
    public static void Show()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<JobHub>();
        context.Clients.All.displayStatus();
    }
}

我有控制器,我在GetData()类中定义了JobInfoRepository方法

 public class JobInfoController : Controller
{

    // GET: /JobInfo/
    JobInfoRepository objRepo = new JobInfoRepository();

    public IEnumerable<JobInfo> Get()
    {
        return objRepo.GetData();
    }
}

我在HomeController中创建了一个名为JobInfo的Action并返回了以下视图

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>JobStatus</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.9.1.min.js")" type="text/javascript"></script>
</head>
<body>
    <div>
        <table id="tblJobInfo" class="clientTable" style="text-align:center;margin-left:10px"></table>
    </div>
</body>
</html>

@section scripts {
    <script src="~/Scripts/jquery.signalR-2.0.1.min.js"></script>
    <script src="/signalr/hubs"></script>
    <script src="~/App/JobInfo.js"></script>
}

检索数据并将其提供给上面的html中的tblJobInfo id,使用java脚本函数

$(function () {
    // Proxy created on the fly
    var job = $.connection.jobHub;

    // Declare a function on the job hub so the server can invoke it
    job.client.displayStatus = function () {
        getData();
    };

    // Start the connection
    $.connection.hub.start();
    getData();
});

function getData() {
    var $tbl = $('#tblJobInfo');
    $.ajax({
        url: '../JobInfo/',
        type: 'GET',
        datatype: 'json',
        success: function (data) {
            if (data.length > 0) {
                $tbl.empty();
                $tbl.append(' <tr><th>ID</th><th>Name</th><th>Status</th></tr>');
                var rows = [];
                for (var i = 0; i < data.length; i++) {
                    rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].Status + '</td></tr>');
                }
                $tbl.append(rows.join(''));
            }
        }
    });
}

在演示中,我发现它工作正常,但是当我转到http://localhost:57044/Home/JobInfo/时,除了没有获得实时通知之外,我在页面上获得了无效数据,如下图所示 enter image description here

我在网上找到的来源是http://techbrij.com/database-change-notifications-asp-net-signalr-sqldependency

0 个答案:

没有答案