asp.net-mvc-3 - 将 Google 图表 API 与 MVC 3 Razor 和 jquery ajax 结合使用

标签 asp.net-mvc-3 razor google-visualization

我正在尝试使用 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);
    }

Controller 代码

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) 外,所有警报都返回正确的值;它返回未定义 并且绘图 div 出现,其中写有标签 No data

最佳答案

我认为您需要在 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); 
    });         
};          

关于asp.net-mvc-3 - 将 Google 图表 API 与 MVC 3 Razor 和 jquery ajax 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10074114/

相关文章:

javascript - 将 Angular JS 数据传递给按钮 OnClick 事件

javascript - 电子表格中的 Google Geochart 动态值

html - 如何将 .css 添加到 .cshtml

python - 使用 Python 将现有字典转换为 JSON

asp.net-ajax - Google 饼图(任何图表)无法在 ASP.Net AJAX 更新面板内工作

asp.net-mvc - ASP.NET MVC 3 简单可靠的移动设备检测 : use 51degrees. mobi 还是原生?

asp.net - Css 在 asp.net mvc3 Razor Views 中不能正常工作

c# - 如何在加载列表框时选择第一个项目

asp.net-mvc-3 - 在部署服务器中编辑 ASP.NET MVC 3 resx 文件,无需重新编译

c# - 显示静态生成数据的 MVC 最佳实践