1

我正在开发一个应用程序,通过该应用程序对数据库的任何更改都将实时更新网页,而无需使用 SignalR 刷新页面

按照我正在使用的代码

1. 型号

public class JobInfo
{
    public int ID { get; set; }
    public string  FirstName { get; set; }
    public string LastName { get; set; }

}

public class JobInfoRepository
{

    public IEnumerable<JobInfo> GetData()
    {
        using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AtlasTest"].ConnectionString))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand(@"SELECT [ID],[FirstName],[LastName]
           FROM [dbo].[Persons]", 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()
                        {
                            ID = x.GetInt32(0),
                            FirstName = x.GetString(1),
                            LastName = x.GetString(2)
                        }).ToList();




            }
        }
    }

    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        JobHub.Show(); 
    }
}

2.控制器

public class AppController : Controller
{
    //
    // GET: /App/
    JobInfoRepository objRepo = new JobInfoRepository();

    public ActionResult Index()
    {
        return View(objRepo.GetData());
    }

}

3.查看

$(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 = $('#Persons');
        $.ajax({
            url: '../api/values',
            type: 'GET',
            datatype: 'json',
            success: function (data) {
                if (data.length > 0) {
                    $tbl.empty();
                    $tbl.append(' <tr><th>ID</th><th>FirstName</th><th>Last Name</th></tr>');
                    var rows = [];
                    for (var i = 0; i < data.length; i++) {
                        rows.push(' <tr><td>' + data[i].ID + '</td><td>' + data[i].FirstName + '</td><td>' + data[i].LastName + '</td></tr>');
                    }
                    $tbl.append(rows.join(''));
                }
            }
        });
    }

4. SignalR 集线器类

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

5. Global.asax.cs

 protected void Application_Start()
    {
         RouteTable.Routes.MapHubs();SqlDependency.Start(ConfigurationManager.ConnectionStrings["AtlasTest"].ConnectionString);
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);


    }

在运行上述代码并通过链接 ..//App/Index. 我得到了以下错误

“/”应用程序中的服务器错误。

传入字典的模型项的类型为“System.Collections.Generic.List 1[GridMvcSignalR.Models.JobInfo]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[GridMvcSignalR.Models.JobInfoRepository]”。

无论如何,我可以修复它并使我的应用程序正常工作。

4

1 回答 1

1

您的顶部似乎有以下声明View

@model IEnumerable<GridMvcSignalR.Models.JobInfoRepository>

尝试将其更改为:

@model List<GridMvcSignalR.Models.JobInfo>
于 2013-09-18T20:50:37.613 回答