【发布时间】:2019-05-20 21:09:47
【问题描述】:
我正在尝试将 ViewBag 更改为 Json 数组以在 .net MVC 框架中绘制图表。我尝试根据我发现以前的问题的解决方案解析 Json,但它什么也没显示。我的代码如下。
控制器
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.Date = dates;
ViewBag.profit = profits;
return View();
}
剃刀视图
<!DOCTYPE HTML>
<html>
<head>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "My First Chart in CanvasJS"
},
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "column",
dataPoints: [
{ label: JSON.parse('@Html.Raw(ViewBag.profit)'), y: JSON.parse('@Html.Raw(ViewBag.Date)') },
]
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
【问题讨论】:
-
你的viewbag的内容不是JSON。为了将 JSON 解析为 JavaScript 对象,您首先要解析的内容实际上需要是 JSON。在服务器端,您需要将变量序列化为 JSON 字符串,然后将该字符串存储在视图包中
标签: javascript json asp.net-mvc