我想将列表中的所有项目添加到ViewBag中。我想要类似的东西:
ViewBag.Date = item1,item2,item3 .....
我的代码仅将列表中的一项(第一个索引)返回到ViewBag。我希望将其分开,因为我想使用该项目在视图中绘制条形图。我也不介意在“剃刀视图”中循环播放。
控制器
public ActionResult RimChart()
{
List<RimCalcs> listOfCategggories = null;
Connectors aConn = Connectors.GetInstance();
listOfCategggories = aConn.GetRimCalc();
//var dates = listOfCategggories.Select(x => x.Date);
// var profits = listOfCategggories.Select(y => y.Rprofit);
ViewBag.list = listOfCategggories;
foreach (RimCalcs c in listOfCategggories)
{
ViewBag.Date = c.Date;
}
foreach (RimCalcs d in listOfCategggories)
{
ViewBag.profit = d.Rprofit;
}
return View();
}
剃刀视图
@Html.Raw(@ViewBag.Date);
@using Newtonsoft.Json;
@{
var profit = JsonConvert.SerializeObject(ViewBag.profit);
var date = JsonConvert.SerializeObject(ViewBag.Date);
}
<!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(date)], //the names displayed on the x-axis, see images below
datasets: [{
label: 'ProductWise Sales Count',
backgroundColor: [
"#f990a7",
"#aad2ed",
"#9966FF",
"#99e5e5",
"#f7bd83",
],
borderWidth: 2,
data: [@profit] //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>
答案 0 :(得分:1)
为什么不将整个listOfCategggories传递给视图。然后只需在json中序列化模型即可。那么您可以在脚本中将模型用作JSON对象
控制器
public ActionResult RimChart()
{
return View(aConn.GetRimCalc());
}
视图
@model List<RimCalcs>
@{
var jsonData = @Html.Raw(Json.Serialize(@Model));
}
<script>
// do your thing
</script>