Google API chart in ASP.NET MVC

2019-06-28 07:03发布

问题:

I am using google apis to create a simplechart

    [AllowAnonymous]
    public JsonResult PieChart()
    {
      return Json("[[\"State\",\"Total\"],[\"GA\",50], [\"AL\",30]]",JsonRequestBehavior.AllowGet);
    }

I am calling this method via ajax from my View. Below is my View

@{
    ViewBag.Title = "Visuals";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Visuals</h2>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {

          var jsonData = $.ajax({
                type: 'GET',
                url: '@Url.Action("PieChart","Home")',
                dataType: "json",
                async: false
           }).responseText;

        var data = google.visualization.arrayToDataTable(jsonData, false);
        var options = {
          title: 'My Daily Activities',
          is3D: true,
        };

        var chart = new google.visualization.PieChart($('#piechart_3d')[0]);
        chart.draw(data, options);
      }

</script>

However I am getting a javascript error on this line saying not an array

var data = google.visualization.arrayToDataTable(jsonData, false);

I have also tried with JSON.Parse but with no success. Thanks for any help.

回答1:

I would try setting the contentType and handling the result in a success handler instead as follows:

      $.ajax({
            type: 'GET',
            url: '@Url.Action("PieChart","Home")',
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            async: false,
            success: function(result) {
                  jsonData = result;
           }
       });

The data you are returning looks ok to me as I tried this:

http://jsfiddle.net/Qquse/547/



回答2:

Unfortunately hutchonoid's answer didn't completely work for me. I had to change the array code to:

object[][] arr = new object[][] { new object[] { "Trickle", "Count" }, new object[] { "Ga", 50 }, new object[] { "Ga", 50 } };