I am trying to develop a web application that displays some charts based on different data that is stored in a database. I found on different tutorials online that I should transfer the data from the controller to the view using a model and then to use Json.Encode for the data to be read correctly by my chart. First it didn't recognize Json.Encode method, so I had to use NuGet Packet Manager to install Microsoft.AspNet.WebPages and when I try to run the app, this error pops up.
I am using .NET Core 5.0
This is where the error comes in:
<script type="text/javascript">
var chart = document.getElementById('pie').getContext('2d');
var myChart = new Chart(chart, {
type: 'pie',
data : @Html.Raw(System.Web.Helpers.Json.Encode(Model.PieChartData)),
});
</script>
This is how I build the model that is given to the view:
public PieChartVM GetPieChartData()
{
var model = new PieChartVM();
var labels = new List<string>();
labels.Add("Green");
labels.Add("Blue");
labels.Add("Gray");
labels.Add("Purple");
model.labels = labels;
var dataset = new List<PieChartChildVM>();
var childModel = new PieChartChildVM();
var backgroundColorList = new List<string>();
var dataList = new List<int>();
foreach(var label in labels)
{
if (label == "Green")
{
backgroundColorList.Add("#2ecc71");
dataList.Add(12);
}
if (label == "Blue")
{
backgroundColorList.Add("#3498db");
dataList.Add(20);
}
if (label == "Gray")
{
backgroundColorList.Add("#95a5a6");
dataList.Add(18);
}
if (label == "Purple")
{
backgroundColorList.Add("#9b59b6");
dataList.Add(50);
}
}
childModel.backgroundColor = backgroundColorList;
childModel.data = dataList;
dataset.Add(childModel);
model.datasets = dataset;
return model;
}