3

I'm trying to display a pie chart in my website using Google charts API so far i cant get it to work and I couldn't find any examples that use MVC 3 Razor.

here is my code im using json to get the data

// 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);
    }

The controller Code

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; }
 }

all the alerts returns correct values except alert(data.length); it returns undefined and the drawing div appears with a label written in it No data

6
  • The Google Chart API is written in JavaScript. So, why are you having trouble with ASP.Net MVC? Commented Apr 9, 2012 at 13:44
  • @Xander I added some code if that helps can you please tell me what am i doing wrong Commented Apr 9, 2012 at 13:47
  • It is wise to give as much detail as possible so that we can better answer your question. It would help if you describe what is happening while the page loads or after it has loaded. Based on the info above I have no idea what is happening on your side. Commented Apr 9, 2012 at 13:51
  • Are you hitting your first alert()? Commented Apr 9, 2012 at 13:52
  • @mgnoonan yes all alerts popup Commented Apr 9, 2012 at 13:58

3 Answers 3

3

I am thinking that you need to move the chart drawing lines inside of the POST callback:

$.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); 
    });         
};          
Sign up to request clarification or add additional context in comments.

4 Comments

Because the post is happening asynchronously, so the program code keeps executing at the next line while the post is taking place. The google.visualization.PieChart line was probably executing before the post completed. So you want the PieChart to draw on a successful completion of the post, which is inside the anonymous post function.
Was wondering why use data.setCell, isn't the JSON array good enough? I would hope one would be able to bind to entire collection and not have to iterate it to set the data.
@JohnPeters Going back too far in my memory, I honestly don't remember. You'll have to conduct your own experiment.
@mgnoonan Ok thanks for posting this it's a good start for me.
0

Google charts API is written in JavaScript so it can be used with any web framework, including ASP.NET MVC. All that you need to do is to include it in your views. It shouldn't be limited or not work because you are using ASP.NET MVC.

Comments

0

After reviewing the full sample of code it looks like the google.setOnLoadCallback(drawChart); is most likely executing the drawChart method before the data is ready. Thus no chart.

Instead of making an Ajax .Post to the server to retrieve data, just build your data on the initial request.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.