I have a line chart http://www.chartjs.org/docs/#line-chart-introduction I want to populate with data from a viewmodel in MVC6/Razor
My Viewmodels are
public class LeaderboardViewModel
{
public List<LeaderboardViewEntry> LeaderboardViewEntries { get; set; }
public HistoicPointsViewModel HistoicPoints { get; set; }
}
public class HistoicPointsViewModel
{
public HistoicPointsViewModel()
{
PlayerHistores = new List<PlayerHistoricViewModel>();
}
public DateTime[] YAxisDates { get; set; }
public List<PlayerHistoricViewModel> PlayerHistores { get; set; }
}
public class PlayerHistoricViewModel
{
public PlayerHistoricViewModel()
{
Points = new List<int?>();
}
public string PlayerName { get; set; }
public List<int?> Points { get; set; }
}
And my view is script section in my View is:
@model Foosball9001.ViewModels.Leaderboards.LeaderboardViewModel
<canvas id="myChart" width="800" height="400"></canvas>
@section Scripts{
<script type="text/javascript">
var data = {
labels: @Model.HistoicPoints.YAxisDates,
datasets: [
{
@foreach (PlayerHistoricViewModel x in Model.HistoicPoints.PlayerHistores)
{
{
label: x.PlayerName,
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: x.Points
}
}
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(data);
</script>
}
So I want to use my HistoicPointsViewModel.YAxisDates as the Y axis coordinates and then I want to create a dataset for each player in my PlayerHistores where it takes the data from PlayerHistoricViewModel.Points as the data to plot into the graph
My problem is writing the dynamic javascript using Razor so it looks like the example
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};