【发布时间】:2015-11-25 14:22:05
【问题描述】:
我正在使用 mvc,我有一个仪表板,我使用了 charthelper 和 bootstrap 管理图表。现在我想更新有关数据库更改的数据。我正在尝试使用信号 R。
之前
我使用存储库从数据库中获取数据。所以有服务文件夹,它有它的方法。
现在。
我不确定该怎么做。 但到目前为止我所做的是创建了一个集线器类, 返回
public static void Send()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<DashboardHub>();
context.Clients.All.updateOnDashboard();
}
正在观看
<script>
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.dashboardHub;
$.connection.hub.logging = true;
chat.client.foo = function () { };
//debugger;
// Create a function that the hub can call to broadcast messages.
chat.client.updateOnDashboard = function () {
getAllDashboardUpdates()
};
$.connection.hub.start().done(function () {
getAllDashboardUpdates();
console.log('Now connected, connection ID=' + $.connection.hub.id);
})
.fail(function () { console.log('Could not connect'); });;
//$.connection.hub.stop();
});
function getAllDashboardUpdates() {
$.ajax({
url: '/Dasdhboard/Index',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
//$("#refTable").html(result);
}).error(function () {
});
}
控制器方法
public ActionResult Index(int? page)
{
IEnumerable<test> newlist = null;
newlist = GetAlltest();
var data = dashboardService.GetDashboardData(page, User);
if (newlist != null)
{
return View(data);
}
return View(data);
}
寻找依赖
public IEnumerable<test> GetAlltest()
{
var messages = new List<test>();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(@"SELECT [id],[testid] FROM [dbo].[test]", connection))
{
command.Notification = null;
SqlDependency.Start(_connString);
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
messages.Add(item: new test { id = (int)reader["id"] });
}
}
}
return messages;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
DashboardHub.Send();
}
}
即使这样做了,我的视图也没有刷新。我确定代码是多余的。有人可以告诉我一个更好的方法来做到这一点。或者我哪里出错了。
这只是一种方法。我也有两张图表。
【问题讨论】:
标签: javascript c# ajax model-view-controller signalr