I am creating some charts in my ASP.NET WebForms aplication and for create the charts in my application, and for the chart’s data, I have to write strings for the datatables (in javascript) like:
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Sold Pencils');
data.addColumn('string', 'title1');
data.addColumn('string', 'text1');
data.addColumn('number', 'Sold Pens');
data.addColumn('string', 'title2');
data.addColumn('string', 'text2');
data.addRows([
[new Date(2008, 1 ,1), 30000, null, null, 40645, null, null],
[new Date(2008, 1 ,2), 14045, null, null, 20374, null, null],
[new Date(2008, 1 ,3), 55022, null, null, 50766, null, null],
[new Date(2008, 1 ,4), 75284, null, null, 14334, 'Out of Stock', 'Ran out of stock on pens at 4pm'],
[new Date(2008, 1 ,5), 41476, 'Bought Pens', 'Bought 200k pens', 66467, null, null],
[new Date(2008, 1 ,6), 33322, null, null, 39463, null, null]
]);
I’m using SqlDataReaders to do this, creating this dirty code:
string jsGraph = "";
jsGraph += "data.addRows([";
while (dsChartsData.Read())
{
var d = (DateTime)dsChartsData["dateColumn"];
jsGraph += "[new Date(" + d.Year.ToString() + ", " + d.Month.ToString() + ", " + d.Day.ToString() + "), " + dsChartsData["value1"].ToString() + ", null, null, " + dsChartsData["value3"].ToString() + ", null, null],";
}
jsGraph += "]);"
Is there any way to do this more maintainable, with a clean code and easy to debug? (javascript in .cs files is a big mess in my code, million of concatenations and stuff)
Obs: Currently I’m using webForms but if some of you have a great advantage doing this with MVC, please tell me, maybe I can create pages in MVC only to renderize charts (after learning that, of course).
First of all, you are missing the separation comma
,from your javascript array…Secondly, why so much concatenations? Why not a public variable and call it from javascript?
like:
In your method:
and in your Javascript:
BTW, your big concatenation should be written as:
witch can be much easier to read.