简体   繁体   中英

Database change updates in ASP.Net MVC 4 using SignalR and SqlDependency

I am working on an application through which any changes to a database will update the webpage at real time without refreshing the page using SignalR

Following the code I am using

1. Model

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. Controller

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

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

}

3. View

$(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 Hub Class

 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);


    }

On running the above code and going through the link ..//App/Index. I got the follwing error

Server Error in '/' Application.

The model item passed into the dictionary is of type 'System.Collections.Generic.List 1[GridMvcSignalR.Models.JobInfo]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1[GridMvcSignalR.Models.JobInfoRepository]'.

Is there anyway, I can fix it and make my application work.

It seems you are having following statement in the top of your View :

@model IEnumerable<GridMvcSignalR.Models.JobInfoRepository>

Try to change it to:

@model List<GridMvcSignalR.Models.JobInfo>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM