Shato Shato - 5 months ago 21
JSON Question

Why Google Chart does not work ASP MVC app?

I have method on my controller, who return Json

[HttpPost]
public JsonResult CompanyChart()
{

var data = db.adusers;
var selectUsers = from s in data where (s.Company != null) select s;
int fenixPlus = (from fP in data where (fP.Company == "ООО \"Феникс+\"") select fP).Count();
int fenixPresent = (from fP in data where (fP.Company == "ООО \"Феникс-Презент\"") select fP).Count();

var dataObj = new object[]
{
new object[] {"Компания","Количество"},
new object[] { "ООО \"Феникс+\"", fenixPlus},
new object[] { "ООО \"Феникс-Презент\"", fenixPresent}
};

return Json(dataObj, JsonRequestBehavior.AllowGet);
}


Json looks like this
[["Компания","Количество"],["ООО \"Феникс+\"",53],["ООО \"Феникс-Презент\"",42]]


In my view side I have a jquery post request

$.ajax({
url: '@Url.Action("CompanyChart", "Users")',
type: 'post',
dataType: "json",
success: function (data) {
drawChart(data);
}
});


Then, I try draw google pie chart

google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
function drawChart(data) {

var array = JSON.parse(data);
var dataV = new google.visualization.DataTable(array);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};

var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(dataV, options);
};


Not work, error in console
Uncaught SyntaxError: Unexpected token К in JSON at position 0


I don't understand, why my code does not work?

Answer

JsonResult returns to the caller a JSON object not a string of JSON content, therefore, you don't need to call JSON.parse.

Simply change

var array = JSON.parse(data);

to

var array = data;