I'm pretty new to c# MVC and would greatly appreciate if you can help me or at least give me an idea on how to solve this. So, I have this method that filters some information from my DB and returns a list (System.Collections.Generic.List`1[Users.AspNetUser]).
private static AspNetUser PopulateModel(string country, [Optional]int Agefrom, [Optional] int Ageto)
{
using (DBEntities entities = DBEntities()) //using ADOnet DB
{
AspNetUser model = new AspNetUser()
{
WebUsers = (from c in entities.AspNetUsers
where c.Country == country || string.IsNullOrEmpty(country)
where c.AgeofUser >= Agefrom && c.AgeofUser <= Ageto || string.IsNullOrEmpty(Agefrom.ToString()) || string.IsNullOrEmpty(Ageto.ToString())
select c).ToList(),
Countries = (from c in entities.AspNetUsers
select new SelectListItem { Text = c.Country, Value = c.Country }).Distinct().ToList(),
Ages = (from c in entities.AspNetUsers
select c.AgeofUser)
};
return model;
}
}
after that I'm trying to display a chart out of that filtered information, but googlecharts asks me for either an array or a datatable to link my data. My problem is that I don't find a way to convert that list to either a DT or an array. I'll leave you the script just in case.
<script>
google.charts.load('current', { 'packages': ['table'] });
google.charts.setOnLoadCallback(drawTable);
function drawTable() {
//here google asks for data in a DT or array with the method arraytotable()
var data = new google.visualization.DataTable(@Model.WebUsers);//here I get "Uncaught SyntaxError: Unexpected end of input" for the bad input
data.addColumn('string', 'Department');
data.addColumn('number', 'Revenues');
data.addRows(data1);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, { showRowNumber: true, width: '100%', height: '100%' });
}
THANKS!
Looking at your code,
You're using the wrong format for initializing the visualizationDataTable and
You only need the WebUsers since it contains all the records already.
Here are 2 options:
You could change your model in your controller to use correct format as shown here https://developers.google.com/chart/interactive/docs/reference. You'll be able to do this with .toJson/JSONStringify or .toArray()
Or an easier option, use the empty initializer and create the variable row with the Webusers records. Modify your script to use the code below;
function drawTable() {
// create row variable, replace u.Name with a string property from your model
var rows = [
@{
foreach(var u in Model.WebUsers){
<text>['@u.Name',@u.AgeofUser],</text>
}
}
]
// use empty initializer
var data = new google.visualization.DataTable();
// add your columns
data.addColumn('string', 'Name');
data.addColumn('number', 'Age');
// add the row variable earlier
data.addRows(rows);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, { showRowNumber: true, width: '100%', height: '100%' });
}