使用Google图表API与MVC 3 Razor和jQuery Ajax

3

我想在我的网站上使用Google图表API显示一个饼图,但目前我无法使其正常工作,也找不到使用MVC 3 Razor的示例。

这是我的代码,我正在使用JSON来获取数据。

// Load the Visualization API and the piechart package.
    google.load('visualization', '1.0', { 'packages': ['corechart'] });

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    JSON.stringify = JSON.stringify || function (obj) {
        var t = typeof (obj);
        if (t != "object" || obj === null) {
            // simple data type
            if (t == "string") obj = '"' + obj + '"';
            return String(obj);
        }
        else {
            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);
            for (n in obj) {
                v = obj[n]; t = typeof (v);
                if (t == "string") v = '"' + v + '"';
                else if (t == "object" && v !== null) v = JSON.stringify(v);
                json.push((arr ? "" : '"' + n + '":') + String(v));
            }
            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
    };
    // Callback that creates and populates a data table,
    // instantiates the pie chart, passes in the data and
    // draws it.
    function drawChart() {

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
        $.post('@Url.Content("~/Home/GetMyChart1")',
            function (items) {
                // Successful requests get here
                alert(JSON.stringify(items) + "   -   " + items.rows.length);
                data.addRows(items.rows.length);
                $.each(items.rows, function (i, item) {
                    alert(i);
                    data.setCell(i, 0, item.Name);
                    data.setCell(i, 1, item.ID);
                });
                alert("finished");
                alert(data.length);
            });
        // Set chart options
        var options = { 'title': 'How Much Pizza I Ate Last Night',
            'width': 400,
            'height': 300
        };

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }

控制器代码
public ActionResult GetMyChart1(string CurrentClass)
    {
        var tests = from t in db.Tests
                    group t by new { t.StudentID, t.Student.CurrentSchoolGrade } into tl
                    select new { StudentID = tl.Key.StudentID, Class = tl.Key.CurrentSchoolGrade, Score = (tl.Sum(k => k.Score)/tl.Sum(l => l.Part.Score))* 100, Count = tl.Count() };
        var results = from t in tests
                      where t.Class == CurrentClass
                      select t;
        List<DataItem> dt = new List<DataItem>();
        dt.Add(new DataItem(results.Count(x => x.Score <= 40), "0% - 40%"));
        dt.Add(new DataItem(results.Count(x => x.Score <= 60 && x.Score > 40), "40% - 60%"));
        dt.Add(new DataItem(results.Count(x => x.Score <= 80 && x.Score > 60), "60% - 80%"));
        dt.Add(new DataItem(results.Count(x => x.Score <= 100 && x.Score > 60), "80% - 100%"));

        chartJson cj = new chartJson();
        cj.rows = dt;

        return Json(cj);
    }
public class chartJson
    {
        public List<DataItem> rows { get; set; }
    }
public class DataItem
{
    public DataItem(int id, string name)
    {
        ID = id;
        Name = name;
    }
    public int ID { get; set; }
    public string Name { get; set; }
 }

所有警报都返回正确的值,除了alert(data.length); 它返回undefined,并且绘图div中出现一个标签,上面写着"无数据"。

Google Chart API是用JavaScript编写的。那么,你为什么在ASP.Net MVC上遇到麻烦呢? - Alex
@Xander,我添加了一些代码,如果有帮助的话,你能告诉我我做错了什么吗? - Shehab Fawzy
最好尽可能提供详细信息,以便我们更好地回答您的问题。如果您描述页面加载时或加载后发生了什么,那将会很有帮助。根据上述信息,我不知道在您这边发生了什么。 - Brendan Vogt
你是否在使用第一个 alert() - mgnoonan
@mgnoonan 是的,所有警告弹出窗口都会出现。 - Shehab Fawzy
@ShehabFawzy,你从“GetMyChart1”返回了什么?...你能发布一下这个操作吗?提前感谢! - Romias
3个回答

3
我认为您需要将图表绘制线移至POST回调函数内部:
$.post('@Url.Content("~/Home/GetMyChart1")', function (items) {
    // Successful requests get here                 
    alert(JSON.stringify(items) + "   -   " + items.rows.length);                 
    data.addRows(items.rows.length);                 
    $.each(items.rows, function (i, item) { 
        alert(i);                     
        data.setCell(i, 0, item.Name);                     
        data.setCell(i, 1, item.ID);                 
    });                 
    alert("finished");                 
    alert(data.length);             
    // Set chart options         
    var options = { 
        'title': 'How Much Pizza I Ate Last Night',             
        'width': 400,             
        'height': 300         
        // Instantiate and draw our chart, passing in some options.         
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));   
        chart.draw(data, options); 
    });         
};          

由于该帖子是异步发生的,因此程序代码在帖子进行时会继续执行下一行。google.visualization.PieChart 行可能在帖子完成之前执行。因此,您希望 PieChart 在成功完成帖子后绘制,这是在匿名帖子函数内部完成的。 - mgnoonan
想知道为什么要使用data.setCell,JSON数组不够好吗?我希望能够绑定整个集合而不必迭代它来设置数据。 - JWP
1
@JohnPeters 回忆太久远了,老实说我不记得了。你需要进行自己的实验。 - mgnoonan
@mgnoonan 好的,谢谢你发布这个,对我来说是一个很好的开始。 - JWP

0

Google图表API是用JavaScript编写的,因此它可以与任何Web框架一起使用,包括ASP.NET MVC。您只需要在视图中包含它即可。它不应该受到限制或因为您使用ASP.NET MVC而不起作用。


0
在查看完整个代码示例后,似乎google.setOnLoadCallback(drawChart);data准备好之前最有可能执行drawChart方法。 因此没有图表。
与其进行Ajax .Post 到服务器检索数据,不如在初始请求中构建数据。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接