1

SignalR を使用してページを更新することなく、データベースへの変更がリアルタイムで Web ページを更新するアプリケーションに取り組んでいます。

私が使用しているコードに従って

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.グローバル.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