Chart.js Asp.net : Create Pie chart with database jQuery Ajax C#

/ / 6 Comments
Pie Chart using ChartJs Asp.net:   This article explains using Chart.js in Asp.net C# Web Application we can create a pie chart with database MS SQL server connectivity via jQuery ajax call.  You can also have a look at related article Chartjs: simple Pie chart example, Chart.Js: Simple bar chart example using html5 canvas jQuery. Now in this post here we create a pie chart by using the chart.js library and bind data from our database MS SQL server, with jQuery ajax calling.

Introduction:  Here we are creating a pie chart, which shows data from the database ( MS SQL server).  In my database, I have a table that stores data ( website traffic source info ).

So basically our pie chart data will show traffic source info .i.e. ( how much of page views referral by Facebook, Twitter, google+, Tumblr, etc ).

Chart.js: Simple, clean, and engaging charts for designers and developers developed by Nick Downie. It uses the HTML5 canvas element.

It's supported in all modern browsers, and polyfills support for IE7/8. Chart.js is dependency-free and super lightweight.


# Download - Chart.js file and include in Asp.net Webform

First, download and include the latest files of the chart.js, jQuery library on our web page.

HTML markup under head tag looks like as shown below.

//*
<head runat="server">
    <title>Pie Chart Asp.net with database ms sqlserver</title>
    <script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="js/Chart.js" type="text/javascript"></script>
</head>
//*

 


# Html Markup (Design) - Adding HTML5 Canvas Tag

I have added 2 `drop-down` list control to select the year, month, along with a `button` and a  `canvas` tag.

Now on button click will call jQuery ajax, and then on ajax success our pie chart gets generated by using Chart.js library and the HTML5 Canvas tag

//*
<select id="ddlyear">
    <option>2010</option>
    <option>2011</option>
    <option>2012</option>
    <option>2013</option>
    <option>2014</option>
    <option>2015</option>
</select>
<select id="ddlMonth">
    <option value="1">Jan</option>
    <option value="2">Feb</option>
    <option value="3">Mar</option>.......... ...........</select>
<button id="btnGeneratePieChart">Show</button>
<br/><canvas id="myChart" width="200" height="200"></canvas>

//*
 

# Code Behind - Ajax call WebMethod and returns JSON format data to create Pie Chart

First, add a WebMethod .i.e ASMX file, and then we write our WebMethod which returns `JSON` format data, I must suggest you have a look at detailed article on  Simple jQuery Ajax JSON example in Asp.net C# with SQL database connectivityIn our `.asmx` file will create a class named as trafficSourceData as shown below.

//*
 public class trafficSourceData{
          public string label{get;set;}
          public string value{get;set;}
          public string color{get;set;}
          public string hightlight{get;set;}
    }
//*
 

Now our `WebMethod` will pull data from database Ms Sqlserver for specific month and year, and return list of class object .i.e trafficSourceData class list as JSON formatted data, so our pie chart gets created using chart.js.

//*
[WebMethod]
    public List<trafficSourceData> getTrafficSourceData(List<string> gData)
    {
        List<trafficSourceData> t = new List<trafficSourceData>();
        string[] arrColor = new string[] { "#231F20", "#FFC200", "#F44937", "#16F27E", "#FC9775", "#5A69A6" };

        using (SqlConnection cn = new SqlConnection(conn))
        {
            string myQuery = "select * from traffic_data where YEAR =@year and MONTH=@month";
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = myQuery;
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@year", gData[0]);
            cmd.Parameters.AddWithValue("@month", gData[1]);
            cmd.Connection = cn;
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                int counter = 0;
                while (dr.Read())  {
                    trafficSourceData tsData = new trafficSourceData();
                    tsData.value = dr["visit_count"].ToString();
                    tsData.label = dr["traffic_source"].ToString();
                    tsData.color = arrColor[counter];
                    t.Add(tsData);
                    counter++;
                }
            }
        }
        return t;
    }
//*


# jQuery -  initializing Chart.js in Asp.net WebPage

Now back to client-side coding, we have already done with the server-side code by creating `WebMethod` which returns JSON format data. So now in our Ajax call on success will initialize the Chart.js variable.

Client-side code looks like as written below

//*
$(document).ready(function () {

    $("btnGeneratePieChart").on('click', function (e) {
        e.preventDefault();
        var gData = [];
        gData[0] = $("#ddlyear").val();
        gData[1] = $("#ddlMonth").val();

        var jsonData = JSON.stringify({
            gData: gData
        });
        $.ajax({
            type: "POST",
            url: "WebService.asmx/getTrafficSourceData",
            data: jsonData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess_,
            error: OnErrorCall_
        });

        function OnSuccess_(response) {
            var aData = response.d;
            var arr = [];
            $.each(aData, function (inx, val) {
                var obj = {};
                obj.color = val.color;
                obj.value = val.value;
                obj.label = val.label;
                arr.push(obj);
            });
            var ctx = $("#myChart").get(0).getContext("2d");
            var myPieChart = new Chart(ctx).Pie(arr);
        }

        function OnErrorCall_(response) {}
        e.preventDefault();
    });
});
//*
 

Finally, we are done with coding, Now every time we click a button our pie chart gets created.

Output:

[caption id="attachment_2637" align="aligncenter" width="264"]Chart.js Asp.net : Create Pie chart with database, calling Jquery Ajax Create simple pie chart with database, calling jQuery Ajax[/caption]     You must check these articles:

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

6 Comments

  1. helia chunk 06/25/2015 05:52:48
    Awesome tutorial.. i was searching for chart.js tutorials for long time now .. Thanks a lot Explained very clearly. Nice Website