我的控制器将我的视图呈现为json树,而不是我已实现的饼图。
我尝试使用Viewbag填充数据字段,该Viewbag从浏览器的控制台选项中抛出错误的无效数字。我尝试使用Json从控制器传递数据,该控制器至少从数据库呈现值。
控制器:
private readonly ApplicationDbContext db = new ApplicationDbContext();
[HttpGet]
public ActionResult GetData()
{
List<Fruit> fruitList = new List<Fruit>();
fruitList = db.Fruits.ToList<Fruit>();
ViewBag.FruitNames = (from x in db.Fruits
select x.FruitName).ToList();
return Json(new { data = fruitList },JsonRequestBehavior.AllowGet);
}
**View:**
@{
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.FruitNames)],
datasets: [{
label: 'ProductWise Sales Count',
backgroundColor: [
"#f990a7",
"#aad2ed",
"#9966FF",
"#99e5e5",
"#f7bd83",
],
borderWidth: 2,
url: '/Fruit/GetData',
type: 'GET',
datatype: 'json',
data: [
{ 'Data': 'FruitName', 'name': 'FruitName' },
{'Data': 'FruitQuantity','name':'FruitQuantity'}
]
}]
};
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>
The results of the current operation is as follows:
{"data":[{"Id":1,"FruitName":"Apple","FruitQuantity":25},{"Id":2,"FruitName":"Banana","FruitQuantity":50},{"Id":3,"FruitName":"Pear","FruitQuantity":75},{"Id":4,"FruitName":"Apple","FruitQuantity":20}]}