[Chartjs]-How to Display Chart.js line-chart from a MVC Controller

1👍

data.datasets accepts an array so each item in the array will add another line to the chart.

Here are the steps to "convert" the data from the database to the chart’s format:

  • Use SerializeObject to serilize the table into JSON. It should look something like
[
  { TagsC: 1, TagsN: "Escalation", TagsD: "06 Oct" },
  { TagsC: 7, TagsN: "Switchboard In", TagsD: "06 Oct" },
]
  • Group the records by their TagsN prop (You can do this also in the database itself which is recommended in large data sets). Map can help to do it in a clean way so the outcome is a Map – the keys are the TagsNs and the values are a list of items which have this TagsN.
[[Entries]]
0: {"Escalation" => Array(1)}
1: {"Switchboard In" => Array(7)}
2: {"Account Manager" => Array(5)}
...
  • Convert this to chartjs datasets format.
0: {label: "Escalation", data: Array(1)}
1: {label: "Switchboard In", data: Array(7)}
2: data: (5) [1, 1, 1, 1, 1]
   label: "Account Manager"

Working example:

// this data should come from the server
const colors = ['red', 'blue', 'green', 'yellow'];
const grouped = groupBy(data, 'TagsN');
const lineData = {
  datasets: Array.from(grouped).map(([key, items], index) => ({
    label: key,
    data: items.map(item => item.TagsC),
    backgroundColor: colors[index]
  })),
  labels: Array.from(new Set([...TagsDs]))
};

new Chart(document.getElementById("line-chart").getContext('2d'), {
  type: 'line',
  data: lineData,
  fill: false
});

function groupBy(arr, key) {
  return arr.reduce((prev, current) => {
    const groupKey = current[key];
    if (!prev.has(groupKey)) {
      prev.set(groupKey, []);
    }
    prev.get(groupKey).push(current);
    return prev;
  }, new Map());
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="line-chart" width="800" height="250"></canvas>

<script>
const TagsDs = ["06 Oct","06 Oct","07 Oct","08 Oct","08 Oct","09 Oct","12 Oct","12 Oct","12 Oct","13 Oct","13 Oct","14 Oct","14 Oct","14 Oct","14 Oct"];
const data = [
  { TagsC: 1, TagsN: "Escalation", TagsD: "06 Oct" },
  { TagsC: 7, TagsN: "Switchboard In", TagsD: "06 Oct" },
  { TagsC: 3, TagsN: "Switchboard In", TagsD: "07 Oct" },
  { TagsC: 1, TagsN: "Account Manager", TagsD: "08 Oct" },
  { TagsC: 10, TagsN: "Switchboard In", TagsD: "08 Oct" },
  { TagsC: 4, TagsN: "Switchboard In", TagsD: "09 Oct" },
  { TagsC: 1, TagsN: "Account Manager", TagsD: "12 Oct" },
  { TagsC: 1, TagsN: "Account Manager", TagsD: "12 Oct" },
  { TagsC: 6, TagsN: "Switchboard In", TagsD: "12 Oct" },
  { TagsC: 1, TagsN: "Account Manager", TagsD: "13 Oct" },
  { TagsC: 10, TagsN: "Switchboard In", TagsD: "13 Oct" },
  { TagsC: 1, TagsN: "Account Manager", TagsD: "14 Oct" },
  { TagsC: 6, TagsN: "Switchboard In", TagsD: "14 Oct" },
];
</script>

https://jsfiddle.net/moshfeu/t3o0bvz2/38/

Leave a comment