我已经使用Chart.js创建了一个饼图,并且使用实体框架从SQL服务器数据库中获取了数据。这是在控制器中完成的。
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" width="800" height="800" 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数据库值发生变化时,我需要更新饼图。我们不会刷新整个页面,而只会刷新图表,并且它应该在连续的时间间隔内自动发生。
简单,真的。只需使用chart.config
编辑其属性,然后运行chart.update()
这里是更多信息:https://www.chartjs.org/docs/latest/developers/updates.html