I'm using List to load radar chart from controller. How can i load dynamic labels and data for that chart from controller.
List<MyModel> modelIist = new List<MyModel>();
MyModel model = new MyModel();
model.Data = 1;
model.Label = "First";
modelIist.Add(model);
model = new MyModel();
model.Data = 2;
model.Label = "Second";
modelIist.Add(model);
model = new MyModel();
model.Data = 3;
model.Label = "Third ";
modelIist.Add(model);
ViewBag.radarDesc = modelIist;
I'm loading data above from above list.
<script>
$(document).ready(function () {
var ctx = $("#chart-line");
var myLineChart = new Chart(ctx, {
type: 'radar',
data: {
labels: [], //want to load from the list
/*},*/
datasets: [{
data: [],//want to load from the list
label: "MyData",
borderColor: "#458af7",
backgroundColor: '#458af7',
fill: true
}]
},
options: {
title: {
display: true,
text: '(Max points - 300)'
}
}
});
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js"></script>
<canvas id="chart-line" width="299" height="200" style="display: block; width: 299px; height: 200px;"></canvas>
How can load label: [], data:[] from mvc.
CodePudding user response:
Try this way:
Install Microsoft.AspNetCore.Mvc.NewtonsoftJson
NuGet Package and then serialize the ViewBag.radarDesc
into a valid JavaScript array:
ViewBag.radarDesc = Newtonsoft.Json.JsonConvert.SerializeObject(modelIist);
Then take out the Label
and Data
in the Page and fill it to the appropriate position:
$(document).ready(function () {
var Label = [];
var Data = [];
var radarDesc = @Html.Raw(@ViewBag.radarDesc);
$.each(radarDesc, function (index, value) {
Label.push(value.Label);
Data.push(value.Data);
});
var ctx = $("#chart-line");
var myLineChart = new Chart(ctx, {
type: 'radar',
data: {
labels: Label, //want to load from the list
/*},*/
datasets: [{
data: Data,//want to load from the list
label: "MyData",
borderColor: "#458af7",
backgroundColor: '#458af7',
fill: true
}]
},
options: {
title: {
display: true,
text: '(Max points - 300)'
}
}
});
});
Test Result: