@page
@model DailyRazorPageDemo.Pages.ChartTestModel
<div style="width:400px;">
<canvas id="myChart"></canvas>
</div>
@section scripts{
<script src="~/Chart.js/Chart.js"></script>
<script>
var chartdata = @Html.Raw(Json.Serialize(Model.datalist)); var labels = [];
var data = [];
$.each(chartdata, function (index, value) {
labels.push(value.MyLabel);
data.push(value.MyData);
});
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'demo',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: data
}]
}
});
</script>
}
Here is the result.
Best Regards,
YihuiSun
ASP.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today. Learn more >
Member
3 Points
5 Posts
Razor pages with Chart.js
Apr 08, 2021 04:24 PM|DaddyCool123|LINK
Basic code for chart.js:
I would like to populate labels and data through the page model to get the same outcome.
My model:
public string MyData {get; set;}
public string MyLabel {get; set;}
MyData = "12, 19, 3, 5, 2, 3",
MyLabel = "'Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'"
My Chart.js will be adjusted with the below.
labels: [@Model.MyLabel]
data: [@Model.MyData]
Data works fine, but labels cause some isseus. What do I have to do to populate Labels from the page model?
All-Star
194881 Points
28101 Posts
Moderator
Re: Razor pages with Chart.js
Apr 08, 2021 06:33 PM|Mikesdotnetting|LINK
labels: [@Html.Raw(Model.MyLabel)]
Contributor
3070 Points
873 Posts
Re: Razor pages with Chart.js
Apr 09, 2021 02:48 AM|YihuiSun|LINK
Hi DaddyCool123,
You can use @Html.Raw(Json.Serialize(XXX)).
I wrote an example, you can refer to it.
Model
ChartTest.cshtml.cs
ChartTest.cshtml
Here is the result.
Best Regards,
YihuiSun