C# MVC5 JavaScript Chart.js 饼图,无需刷新即可从 SQL Server 数据库实时更新
Posted
技术标签:
【中文标题】C# MVC5 JavaScript Chart.js 饼图,无需刷新即可从 SQL Server 数据库实时更新【英文标题】:C# MVC5 JavaScript Chart.js Pie Chart with Realtime Updating from SQL Server Database without Refreshing 【发布时间】:2020-02-23 11:33:28 【问题描述】:我使用 Chart.js 创建了一个饼图,并使用实体框架从 SQL-server 数据库中获取数据。这是在控制器中完成的。
namespace ChartJsDatabase.Controllers
public class ChartController : Controller
//============ The Object Created here is used to get the database connection =============
CSharpCornerEntities entities = new CSharpCornerEntities();
//==========================================================================================
// GET: Chart
public ActionResult Index()
return View();
public ActionResult PieChart()
//============= This Action Result Requires ===============
//============= String Database Query =====================
using (entities)//;
var studentName = entities.Database.SqlQuery<PlannedVsActualModel>(@"SELECT [Planned], [Actual] FROM [dbo].[PlanVsActual]").ToList();
return Json( studentName, JsonRequestBehavior.AllowGet);
视图如下
<div class="col-lg-4">
<canvas id="chart_3" http-equiv="refresh" content="5"></canvas>
<h5 style="text-align:center">Total</h5>
</div>
<script type="text/javascript">
$(document).ready(function ()
$.ajax(
type: "GET",
url: "/Chart/PieChart",
data: ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
successFunc(response);
,
);
function successFunc(jsondata)
console.log(jsondata);
window.globalVariable = jsondata;
console.log(globalVariable[0].Actual)
//===========Chart Js Code Starts Here ============
//=================================================
var ctx = document.getElementById('chart_3').getContext('2d');
var chart = new Chart(ctx,
type: 'doughnut',
data:
datasets: [
backgroundColor: ["#228B22", "#f0eeef"],
//========== Data for Chart JS ==============
data: [globalVariable[0].Actual, (globalVariable[0].Planned - globalVariable[0].Actual)],
//===========================================
label: ["Actual", "Planned"],
borderWidth: 0,
]
,
options:
cutoutPercentage: 80,
elements:
center:
text: [(globalVariable[0].Actual/globalVariable[0].Planned*100).toFixed(2)]+"%",
color: '#666666', //Default black
fontStyle: 'Helvetica', //Default Arial
FontSize: 1,
sidePadding: 1 //Default 20 (as a percentage)
);
// ==========Chart Js Chart Ends Here==========
//==============================================
);
</script>
我创建了以下模型
namespace ChartJsDatabase.Models
public class PlannedVsActualModel
public int Planned get; set;
public int Actual get; set;
当 SQL Server 数据库值发生变化时,我需要更新饼图。我们不会刷新整个页面,只会刷新图表,它应该会在连续的时间间隔内自动发生。
【问题讨论】:
【参考方案1】:很简单,真的。只需使用chart.config
编辑它的属性,然后运行chart.update()
这里有更多信息:https://www.chartjs.org/docs/latest/developers/updates.html
【讨论】:
【参考方案2】:您可以通过多种方式实现它,这里是带有部分视图的一种
a) Create a partial view and include it with your page
<Div id="pieChart">
@HTML.Partial("__pieChartPartial" , chartdata)
</Div>
b) write a jquery script in page
<script>
setInterval(function()
$('#__pieChartPartial').load("controller/action"),1000); # adjust interval time based on your requirement
</script>
c) In the action method return partial view result
Return PartialView("__pieChartPartial", chartdata)
d) Make output cache, nostore and set duration to 1 min
[OutputCache(NoStore=true,Location=System.Web.UI.OutputCacheLocation.Client,Duration=1)]
e) Enable sql broker.
f) Install-Package SqlTableDependency
g) Write a code for table watcher and start watching in controller's constructor
h) In table dependency change event, refresh chart data.
【讨论】:
以上是关于C# MVC5 JavaScript Chart.js 饼图,无需刷新即可从 SQL Server 数据库实时更新的主要内容,如果未能解决你的问题,请参考以下文章
C# MVC5 @Html.EnumDropDownListFor 在“回发”上丢失选择
C# mvc5使用mvc5 +bootstrap+EF6搭建一个权限管理系统的心得体会
如何使用对象 MVC 5 C# 的 Javascript 列表填充剃刀 DropDownListFor
从控制器获取结果,但在 MVC5 和 C# 中,ajax 调用获取错误而不是成功