score:19
retrieving data from database multiple-line charts in chart.js using asp.net,c#
here is the code
<script type="text/javascript">
$(document).ready(function () {
debugger;
$.ajax({
type: "post",
contenttype: "application/json; charset=utf-8",
url: "campcomparison.aspx/getlinechartdataload",
data:{},
async: true,
cache: false,
datatype: "json",
success: onsuccess_,
error: onerrorcall_
})
function onsuccess_(reponse) {
var adata = reponse.d;
var alabels = adata[0];
var adatasets1 = adata[1];
var adatasets2 = adata[2];
var adatasets3 = adata[3];
var adatasets4 = adata[4];
var adatasets5 = adata[5];
var linechartdata = {
labels: alabels,
datasets: [
{
label: "data1",
//fill:false,
fillcolor: "rgba(0,0,0,0)",
strokecolor: "rgba(220,220,220,1)",
pointcolor: "rgba(200,122,20,1)",
data: adatasets1
},
{
label: "data2",
fillcolor: 'rgba(0,0,0,0)',
strokecolor: 'rgba(220,180,0,1)',
pointcolor: 'rgba(220,180,0,1)',
data: adatasets2
},
{
label: "data5",
fillcolor: "rgba(0,0,0,0)",
strokecolor: "rgba(151,187,205,1)",
pointcolor: "rgba(152,188,204,1)",
data: adatasets3
},
{
label: "data4",
fillcolor: 'rgba(0,0,0,0)',
strokecolor: 'rgba(151,187,205,1)',
pointcolor: 'rgba(151,187,205,1)',
data: adatasets4
},
{
label: "data4",
fillcolor: 'rgba(0,0,0,0)',
strokecolor: 'rgba(151,187,205,1)',
pointcolor: 'rgba(151,187,205,1)',
data: adatasets5
},
]
}
chart.defaults.global.animationsteps = 50;
chart.defaults.global.tooltipypadding = 16;
chart.defaults.global.tooltipcornerradius = 0;
chart.defaults.global.tooltiptitlefontstyle = "normal";
chart.defaults.global.tooltipfillcolor = "rgba(0,160,0,0.8)";
chart.defaults.global.animationeasing = "easeoutbounce";
chart.defaults.global.responsive = true;
chart.defaults.global.scalelinecolor = "black";
chart.defaults.global.scalefontsize = 16;
//linechart.destroy();
//document.getelementbyid("canvas").innerhtml = ' ';
//document.getelementbyid("chartcontainer").innerhtml = ' ';
//document.getelementbyid("chartcontainer").innerhtml = '<canvas id="canvas" style="width: 650px; height: 350px;"></canvas>';
//var ctx = document.getelementbyid("canvas").getcontext("2d");
//ctx.innerhtml = "";
//var piechartcontent = document.getelementbyid('piechartcontent');
//piechartcontent.innerhtml = ' ';
//$('#piechartcontent').append('<canvas id="canvas" width="650px" height="350px"><canvas>');
//ctx = $("#canvas").get(0).getcontext("2d");
var ctx = document.getelementbyid("canvas").getcontext("2d");
var linechart = new chart(ctx).line(linechartdata, {
beziercurve: true,
chartarea: { width: '62%' },
responsive: true,
pointdotradius: 10,
scaleshowverticallines: false,
scalegridlinecolor: 'black'
});
}
function onerrorcall_(repo) {
//alert(repo);
}
});
//});
</script>
c#code
--------
[webmethod(enablesession = true)]
public static list<object> getlinechartdataload()
{
list<object> idata = new list<object>();
list<string> labels = new list<string>();
string advertiserid = httpcontext.current.session["accountid"].tostring();
if (!string.isnullorempty(advertiserid))
{
// string startdate = datetime.now.adddays(-180).tostring("yyyy-mm-dd");
string startdate = datetime.now.adddays(-60).tostring("yyyy-mm-dd");
string enddate = datetime.now.tostring("yyyy-mm-dd");
string strcampaignid = string.empty;
datatable dt = new datatable();
int i = 0;
chatbl objcampid = new chatbl();
string query = "select distinct top 3 campaignid,campaignname from campaign where advertiserid='" + advertiserid + "' order by campaignname";
dt = objcampid.commonfuntiongetdata2(query);
foreach (datarow drow in dt.rows)
{
strcampaignid += drow["campaignid"].tostring() + ",";
}
if (!string.isnullorempty(strcampaignid))
{
strcampaignid = strcampaignid.substring(0, strcampaignid.length - 1);
}
string[] campaignid = strcampaignid.split(',');
//first get distinct month name for select year.
// string query1 = "select top 10 cast(createddatetime as date) as month_name from advertiser where currentbal>0 order by currentbal";
//query1 += " ";
// query1 += " order by month_number;";
foreach (string strcamp in campaignid)
{
if (i == 0)
{
chatbl objblabel = new chatbl();
// datatable dtlabels = objblabel.topupmonthly("5e8ef1e9-67bf-489c-84cb-aff0bb0fe707", "2015-09-18", "2016-02-25", "months");
datatable dtlabels = objblabel.topupmonthly2(strcamp, startdate, enddate, "months");
foreach (datarow drow in dtlabels.rows)
{
labels.add(drow["insdatetime"].tostring().substring(2, 7));
}
idata.add(labels);
}
// string query_dataset_1 = "select top 10 currentbal from advertiser where currentbal>0 order by currentbal";
//query_dataset_1 += " (orders_quantity) as total_quantity from mobile_sales ";
//query_dataset_1 += " where year(orders_date)='" + year + "' and mobile_id='" + mobileid_one + "' ";
//query_dataset_1 += " group by month(orders_date) ";
//query_dataset_1 += " order by month_number ";
chatbl objbl = new chatbl();
datatable dtdataitemssets_1 = objbl.topupmonthly2(strcamp, startdate, enddate, "months");
list<double> lst_dataitem_1 = new list<double>();
foreach (datarow dr in dtdataitemssets_1.rows)
{
lst_dataitem_1.add(convert.todouble(dr["cpacount"].tostring()));
}
idata.add(lst_dataitem_1);
//string query_dataset_2 = "select top 10 totalspent from advertiser where currentbal>0 order by currentbal";
//query_dataset_2 += " (orders_quantity) as total_quantity from mobile_sales ";
//query_dataset_2 += " where year(orders_date)='" + year + "' and mobile_id='" + mobileid_two + "' ";
//query_dataset_2 += " group by month(orders_date) ";
//query_dataset_2 += " order by month_number ";
//chatbl objbl1 = new chatbl();
//datatable dtdataitemssets_2 = objbl1.topupmonthly("5e8ef1e9-67bf-489c-84cb-aff0bb0fe707", "2015-09-18", "2016-02-25", "months");
//list<double> lst_dataitem_2 = new list<double>();
//foreach (datarow dr in dtdataitemssets_2.rows)
//{
// lst_dataitem_2.add(convert.todouble(dr["cpacount"].tostring()));
//}
//idata.add(lst_dataitem_2);
i = i + 1;
}
}
return idata;
}
score:22
you were creating inserting the same object (dataset) at all 4 locations of the dataset. so any manipulations in the loop are being done on all of the array elements (actually it would be more accurate to say that it's being done on dataset and that dataset is there at all 4 indices of the array)
notice that in the following code the {} object literal is actually being inserted 4 times into the array giving you a fresh element each time.
linechartdata = {}; //declare an object
linechartdata.labels = []; //add 'labels' element to object (x axis)
linechartdata.datasets = []; //add 'datasets' array element to object
for (line = 0; line < 4; line++) {
y = [];
linechartdata.datasets.push({}); //create a new line dataset
dataset = linechartdata.datasets[line]
dataset.fillcolor = "rgba(0,0,0,0)";
dataset.strokecolor = "rgba(200,200,200,1)";
dataset.data = []; //contains the 'y; axis data
for (x = 0; x < 10; x++) {
y.push(line + x); //push some data aka generate 4 distinct separate lines
if (line === 0)
linechartdata.labels.push(x); //adds x axis labels
} //for x
linechartdata.datasets[line].data = y; //send new line data to dataset
} //for line
ctx = document.getelementbyid("chart1").getcontext("2d");
mylinechart = new chart(ctx).line(linechartdata);
// for chart.js 2.0 the following will be to create `mylinechart`
// mylinechart = new chart(ctx1, {
// type: 'line',
// data: linechartdata,
// });
i also made a small change for your labels - you just need 1 set of labels.
to draw an analogy, the original code was doing this
series a = new series()
array chartdata = []
for (var i = 0; i < 4; i++) {
chartdata.add(a);
-- some modifications on a ---
}
at the end of this you basically have an array with 4 pointers to the same object a
.
fiddle - http://jsfiddle.net/tk78bosy/
Source: stackoverflow.com
Related Query
- create a multi line chart using Chart.js
- How to create a line on a chart using chartjs-plugin-annotation
- Create a line chart using an user input table from a data table in chart.js
- how to create line chart using chart.js in angular 2+
- Using custom dataformat in chart.js for Multi Axis Line Chart
- How can I create a horizontal scrolling Chart.js line chart with a locked y axis?
- Moving vertical line when hovering over the chart using chart.js
- How to add an on click event to my Line chart using Chart.js
- Display line chart with connected dots using chartJS
- How to create stacked bar chart using react-chartjs-2?
- Display a limited number of labels only on X-Axis of Line Chart using Chart.js
- How to create a gradient fill line chart in latest Chart JS version (3.3.2)?
- How to create single value Doughnut or Pie chart using Chart.js?
- Create multiple dynamic stacked chart using chart.js in Angular 10?
- chartjs - multi axis line chart - cannot read property 'min' of undefined
- How to create a gantt chart using Chart.js and populate dates?
- Create Chart using Reactjs Chartjs and axios
- Add data to line chart using chart.js
- Change Axis Line color in Chart created using chart.js
- Displaying line chart for multiple months using chart.js
- How to make aspecific API call from within a Line Chart class in ReactJS using react-chartjs-2?
- Chart JS: Always show tooltips in a multi dataset line chart
- display vertical axis label in line chart using chart.js
- how can i use chart.js to create a chart that has one time series line and one linear line on it at the same time?
- create Chart using Chartjs and PHP
- Adding data to line chart using addData() method in Chart.js
- How to create Waterfall model chart using QuickChart?
- How to create a bar and a line in a same graph using chart.js in React?
- How to create a line chart indicating which month a user wrote more or less blogs?
- Line Chart using Chart js with time data
More Query from same tag
- how to format date string for x axis labels in chartjs?
- Vue chartjs is not rendering from API
- How to update JS variable in value field of charts.js?
- How to differentiate the data of one topic or another coming from Mercure hub if the client is suscribed to two topics
- Dynamically updating Chart.js data in angular
- Angular: How to change color of chartjs?
- How to make labels on both side from horizontal bar chart js
- Providing server side data for Chart.js charts
- Chartjs show labels but not ticks
- Chartjs - how to make line position to vertical center and how to display dotted sharp in the backround?
- Automatic update a ChartJs with SQL
- I am having this error in charts v3 chartjs-chart-treemap: fontColor does not exist in type 'ChartDataset<"treemap", TreemapDataPoint[]>
- Chart JS Tooltip Currency Problem - Stacked Bar Chart
- How to eliminate all borders from chartjs2 stacked chart
- Chart.js legend text showing undefined
- Remove background on Chartjs v2 fixed tooltips
- Chart.js Bubble chart with custome X-axis labels
- How to change bar width individually in chartjs?
- Chart Js + Angular
- How can I remove the grid line in the background of the line chart?
- Issue with int numbers using chart.js
- Php array and chartjs
- Chart.js pie chart overflowing div
- Accessing data from the callback function of a bar chart using chart js
- How can I force my ChartJS canvas legend to stay in a single column?
- How to color legend in angular-chart.js
- Reactive Vue Chart.js component using Typescript
- ChartJS:align zeros on chart with multi axes
- Chart JS - Horizontal Bar Chart Not Filling Canvas
- chart.js Legends issue (not showing)