gpt4 book ai didi

javascript - 将列表中的项目循环到 Controller 中的 ViewBag 中

转载 作者:行者123 更新时间:2023-12-02 23:35:10 24 4
gpt4 key购买 nike

我想将列表中的所有项目添加到 ViewBag 中。我想要这样的东西:

ViewBag.Date = item1, item2, item3.....

我的代码仅将列表中的一个项目(第一个索引)返回到 ViewBag 中。我希望将其分开,因为我想使用该项目在 View 中绘制条形图。我也不介意在 Razor View 中循环。

Controller

   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();
}

Razor 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>

最佳答案

为什么不将整个 listOfCategggories 传递给 View 。然后将模型序列化为 json 即可。那么你可以在脚本中使用模型作为 JSON 对象

Controller

  public ActionResult RimChart()
{
return View(aConn.GetRimCalc());
}

查看

  @model List<RimCalcs> 
@{
var jsonData = @Html.Raw(Json.Serialize(@Model));
}

<script>
// do your thing
</script>

关于javascript - 将列表中的项目循环到 Controller 中的 ViewBag 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56318412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com