I need to create a chart with two lists.
List<string> islemYapanOperatorler = new List<string>();
List<int> interventionCounter = new List<int>();
foreach (var item in itemList)
{
string Normalize = item.Key;
for (int i = 0; i < turkishChars.Length; i )
Normalize = Normalize.Replace(turkishChars[i], englishChars[i]);
islemYapanOperatorler.Add(Normalize);
foreach (var item2 in item)
{
interventionCount ;
}
interventionCounter.Add(interventionCount);
interventionCount = 0;
operatorCount ;
}
islemYapanOperatorler list is creates the label part and interventioncounter list is creating the data part for Chart.Js.
And javascript code for Chart.js below: (It's a bit lazy but it gives the result I want.)
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels:
['@islemYapanOperatorler[0]', '@islemYapanOperatorler[1]', '@islemYapanOperatorler[2]', '@islemYapanOperatorler[3]', '@islemYapanOperatorler[4]', '@islemYapanOperatorler[5]', '@islemYapanOperatorler[6]', '@islemYapanOperatorler[7]', '@islemYapanOperatorler[8]', '@islemYapanOperatorler[9]', '@islemYapanOperatorler[10]']
,
datasets: [{
label: 'Haftalık',
data: [@interventionCounter[0], @interventionCounter[1], @interventionCounter[2], @interventionCounter[3], @interventionCounter[4], @interventionCounter[5], @interventionCounter[6], @interventionCounter[7], @interventionCounter[8], @interventionCounter[9], @interventionCounter[10]],
backgroundColor: [
'rgba(0, 26, 190, 0.8)'
],
borderColor: [
'rgba(0, 26, 190, 1)'
],
borderWidth: 1
}
]
},
options: {
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
return data['labels'][tooltipItem['index']] ': ' data['datasets'][0]['data'][tooltipItem['index']] ;
}
}
},
scales: {
y: {
beginAtZero: true
}
}
}
});
It's working correctly and gives the result I want. (picture below)
But, as you can see
It works fine for 11 indices, but this number of indices may vary. In such a case, either it does not show the data in the 12th index because it is defined as a constant 11 index, or it fails because the 11th index is empty.
How can I solve this problem? Thanks for any suggestions.
CodePudding user response:
After a deep research:
var model = @Html.Raw(Json.Serialize(interventionCounter));
var monthlyData = [];
$.each(model, function (index, item) {
monthlyData .push(item.toString());
});
then at the Chartjs script:
data: monthlyData,
solved my question. I'm marking this answer in order to help others in the future.