Reputation: 153
I am trying to change ViewBag to Json array to plot a chart in .net MVC framework. I try to parse Json based on solution I found previous questions but it displays nothing. My code is below.
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.Date = dates;
ViewBag.profit = profits;
return View();
}
Razor 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>
Upvotes: 1
Views: 1791
Reputation: 730
Edited You may want to serialize first and the do the parse
@{
var profit = JsonConvert.SerializeObject(ViewBag.profit);
var date = JsonConvert.SerializeObject(ViewBag.Date);
}
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(profit)'), y: JSON.parse('@Html.Raw(date)') },
]
}
]
});
chart.render();
}
Or you can Serialize directly on the 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.Date = JsonConvert.SerializeObject(dates);
ViewBag.profit = JsonConvert.SerializeObject(profits);
return View();
}
Upvotes: 3