Tag Archives: Google

Creating responsive and mobile friendly charts with Ajax and C# in asp.net

Google’s chart API is really amazing. with it, you can create responsive and mobile friendly chats that users can interact with. following is a small guideline to pass parameters to asp.net WebMethod with parameters  and draw charts with returned  Json result.

Page we are referring to is Reports_Sales_SalesByCategory.aspx. note that i have a DropDownList( ID=”DropDownList1″) and DIV tag (chart_SalesOverview) in this page  rest of the code is just for styling and you can simply ignore

</pre>
<div id="reportDiv" class="col-md-8 col-sm-8">
<div class="panel panel-default">
<div class="panel-heading">
<h4>Select Range</h4>
</div>
<div class="panel-body">
                    <!--Div that will hold the pie chart-->
<div class="form">
<div class="input-group text-center">
                            <asp:DropDownList ClientIDMode="Static" ID="DropDownList1" class="form-control input-lg" runat="server">
                                Last Week
                                Last Month</div>
</div>
<div id="chart_SalesOverview"></div>
</div>
</div>
</div>
<pre>

Next thing is to write a WebMethod that return Json result in code behind so that we can call this method via AJAX.
Make sure to add [WebMethod] and [ScriptMethod(ResponseFormat = ResponseFormat.Json)] annotations to the method as shown. so that Ajax can discover the method. and method should be public static as well.


 [WebMethod]
 [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

  public static object[] GetChartData(int days)
  {
       List data = new List();

       data.Add(new GoogleChartData { ProductCategory = "Cat 1", RevenueAmount = 100 });
       data.Add(new GoogleChartData { ProductCategory = "Cat 2", RevenueAmount = 200 });
       data.Add(new GoogleChartData { ProductCategory = "Cat 3", RevenueAmount = 300 });

       var chartData = new object[data.Count + 1];
       chartData[0] = new object[]
        {
           "Product Category",
           "Revenue Amount"
        };
        int j = 0;
        foreach (var i in data)
        {
          j++;
          chartData[j] = new object[] { i.ProductCategory, i.RevenueAmount };
        }

         return chartData;
    }

now that we have method that return some data, we’ll jump back to aspx file where we left off. next step is to add reference to google’s Chart API. to do that add following script reference


<script src="Scripts/jquery-2.1.1.min.js">
</script><script src="https://www.google.com/jsapi" type="text/javascript"></script>

after that we have to write our java script to pull the data from our web method and draw the chart.
in this example we’ll be drawing a Pie chart.

    <script>

        var chartData;
        google.load("visualization", "1", { packages: ["corechart"] });

        $(document).ready(function () {
            var parameters = {};
            parameters.days = $('#<%= DropDownList1.ClientID %>').val();

           // call web method with parameters
            $.ajax({
                url: "Reports_Sales_SalesByCategory.aspx/GetChartData",
                data: JSON.stringify(parameters),
                dataType: "json",
                type: "POST",
                contentType: "application/json; chartset=utf-8",
                success: function (data) {
                    chartData = data.d;
                },
                error: function () {
                    alert("Something went wrong! Please try again.");
                }
            }).done(function () {
                // after complete loading data
                google.setOnLoadCallback(drawChart);
                drawChart();
            });
        });

        function drawChart() {
            var data = google.visualization.arrayToDataTable(chartData);

            var options = {
                title: "Company Sales",
                pointSize: 5
            };

            var pieChart = new google.visualization.PieChart(document.getElementById('chart_SalesOverview'));
            pieChart.draw(data, options);
        }

</script>

please note that its better to render java script part  just before the end of  <HEAD> element.

Enjoy !!

What if something is wrong..

  • check your Script reference is correct and well placed.
  • make sure server control’s Client ID mode is static or you will have to get the client ID via Jquery and replace it with existing one.
  • make sure javascript’s parameter object contain variables with same names as web method’s parameters.

Reference :  Google Chart API