问题描述
我正在使用mvc,我有一个仪表板,我使用了charthelper和bootstrap管理图表。现在我想更新有关数据库更改的数据。我试图使用信号R.
之前
我使用存储库来获取数据来自数据库。所以有服务文件夹有方法。
现在。
我不确定怎么做。
但到目前为止我所做的是创建了一个集线器类,
返回
I'm using mvc, i have a dashboard for which i have used charthelper and bootstrap admin chart. Now i want to update the data on database change. For which i'm trying to use signal R.
Before
I used repository to get data from database. So had services folder which had methods for it.
Now.
I'm not sure exactly how to do it.
But what i have done so far is created a hub class,
returning
public static void Send()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<DashboardHub>();
context.Clients.All.updateOnDashboard();
}
和视图
and on view
<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 () {
});
}
</script>
控制器方法
controller method
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);
}
搜索相关性
to search for dependency
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();
}
}
即使这样做了我的观点也没有刷新。我确信代码是多余的。有人告诉我一个更好的方法。或者我哪里出错了。
这只是一种方法。我也有2个图表。
Even after doing it my view is not refreshed. I'm sure code is redundant. CAn someone show me a better way to do it. Or where i'm going wrong.
This is just one method. I have 2 charts too.
推荐答案
这篇关于如何在使用信号r更新数据库更改时刷新视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!