There are no errors and ajax is able to make a success call and return data from GetData()
. I am using google charts api
Question: How can i convert List into google api datable?
Issue: Google chart api - takes data in following format
var data = new google.visualization.DataTable();
data.addColumn('string', 'First_name ');
data.addColumn('string', 'Salary');
data.addColumn('boolean', 'Full_Time_Employee ');
data.addRows([
['Mike', '$10,000', true],
['Jim', '$8,000', false],
['Alice', '$12,500', true],
['Bob', '$7,000', true]
]);
but When i get data from database, that it doesnt display anything bc formating is not the same on line return Json(graphData);
{ First_Name = "Mike", Salary= "10000", Full_Time_Employee = true }
Controller:
public async Task<IActionResult> GetData()
{
try
{
// query data
IQueryable<MyModel> query = (IQueryable<MyModel>)(from x in _context1.CourseTaken_DbSet
select x);
//load data
List<MyModel> graphData = await query.AsNoTracking().Take(100).ToListAsync();
// return json data to google charts api
return Json(graphData);
}
catch (Exception ex)
{
Console.Write(ex);
}
return View();
}
Font-end
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["table"] });
google.setOnLoadCallback(drawChart01);
function drawChart01() {
alert('testing1');
var googleApiClass = {
'headerRow': 'header-style',
'tableCell': 'table-rows'
};
var options = {
title: 'Total',
'is3D': true,
'width': '100%',
'height': '100%',
cssClassNames: googleApiClass
};
$.ajax({
type: "POST",
url: "/Home/GetData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert("sucess" r.d);
var data = new google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.Table($("#Chart01Div")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert("Failure: " r.d);
},
error: function (r) {
alert("Error: " r.d);
}
});
} //end of drawChart01 function
I also Tried - but this returns object Object],[object Object],[object Object],[object Object],[object Object],[object Object],
success: function (r) {
alert(r);
var data = new google.visualization.arrayToDataTable(r);
var chart = new google.visualization.Table($("#Chart01Div")[0]);
chart.draw(data, options);
},
CodePudding user response:
You can perform the data conversion from the list of objects to a two-dimension array on JavaScript side as below:
var data = new google.visualization.DataTable();
data.addColumn('string', 'First_name');
data.addColumn('string', 'Salary');
data.addColumn('boolean', 'Full_Time_Employee');
var rows = [];
$.each(r, function (i, obj) {
rows.push([obj.First_Name, obj.Salary, obj.Full_Time_Employee]);
});
data.addRows(rows);
var chart = new google.visualization.Table($("#Chart01Div")[0]);
chart.draw(data, options);