看看这个链接:http://www.c-sharpcorner.com/article/create-free-charts-using-chart-js-in-asp-net-mvc/
它描述了在 mvc 中使用图表的所有相关步骤。
让我们说这是你的控制器方法:
public ActionResult Index()
{
ViewBag.Data = "Value,Value1,Value2,Value3"; //list of strings that you need to show on the chart. as mentioned in the example from c-sharpcorner
ViewBag.ObjectName = "Test,Test1,Test2,Test3";
}
您可以在视图包中返回数据并将它们传递给图表的数据属性:
这是你的观点:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Charts</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>
<script>
var barChartData =
{
labels: [@Html.Raw(ViewBag.ObjectName)], //the names displayed on the x-axis, see images below
datasets: [{
label: 'ProductWise Sales Count',
backgroundColor: [
"#f990a7",
"#aad2ed",
"#9966FF",
"#99e5e5",
"#f7bd83",
],
borderWidth: 2,
data: [@ViewBag.Data] //what you returned back from controller. values displayed on the y-axis, see images below
}]
};
window.onload = function () {
var ctx1 = document.getElementById("barcanvas").getContext("2d");
window.myBar = new Chart(ctx1,
{
type: 'bar',
data: barChartData,
options:
{
title:
{
display: true,
text: "ProductWise Sales Count"
},
responsive: true,
maintainAspectRatio: true
}
});
}
</script>
</head>
<body>
<div style="text-align: center">
<canvas id="barcanvas"></canvas>
</div>
<div style="text-align: center">
Disclaimer:- This data is for demo it is
not real data it wont relate to any company
</div>
</body>
</html>