locked
Pie Chart using Chart.js using asp.net with database RRS feed

  • Question

  • User1152553138 posted

    I tried the below tutorials ... But unable to generate chart

    https://codepedia.info/chartjs-asp-net-create-pie-chart-with-database-calling-jquery-ajax-c/

    See my code detail

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    
        <script src="jquery-3.3.1.min.js" type="text/javascript"></script>
        <script src="chart.js" type="text/javascript"></script>
    
    </head>
    <body>
        <form id="form1" runat="server">
        
    
        <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/>
    
    <script type="text/javascript">
    
        $(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();
            });
        });
    
    </script>
    
    
    <canvas id="myChart" width="200" height="200"></canvas>
    
    
        </form>
    </body>
    </html>
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Text;
    using System.Web.Services;
    using System.Data.SqlClient;
    using System.Configuration;
    
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        public class trafficSourceData
        {
            public string label { get; set; }
            public string value { get; set; }
            public string color { get; set; }
            public string hightlight { get; set; }
        }
    
        [WebMethod]
    
        public List<trafficSourceData> getTrafficSourceData(List<string> gData)
        {
            List<trafficSourceData> t = new List<trafficSourceData>();
            string[] arrColor = new string[] { "#231F20", "#FFC200", "#F44937", "#16F27E", "#FC9775", "#5A69A6" };
    
            string conn = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    
            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;
        }
    
    }

    I am getting uncaught reference error... See the link

    https://www.photobox.co.uk/my/photo/full?photo_id=500997909239

    Error

    Friday, August 24, 2018 12:52 PM

Answers

  • User283571144 posted

    Hi Ashraf007,

    Thanks you all ... As per your suggestion i tried the below method ... The chart is not rendering ....

    According to your description and code,I suggest you could add static for the webmethod in code-behind and add # before id to locate the  btnGeneratePieChart button in js code.

    For more details, you could refer to the code below.

    .aspx

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js" type="text/javascript"></script>
        <script>
            $(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: "PieChart.aspx/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);
                        });
                        console.log(arr);
                        var ctx = $("#myChart").get(0).getContext("2d");
                        var myPieChart = new Chart(ctx).Pie(arr);
                    }
    
                    function OnErrorCall_(response) { }
                    e.preventDefault();
                });
    
            });
    
    
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <select id="ddlyear">
                    <option>2010</option>
                    <option>2011</option>
                    <option>2012</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>
            </div>
        </form>
    </body>
    </html>
    

    Code-behind:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Text;
    using System.Web.Services;
    using System.Data.SqlClient;
    using System.Configuration;
    public class trafficSourceData
            {
                public string label { get; set; }
                public string value { get; set; }
                public string color { get; set; }
                public string hightlight { get; set; }
            }
    
            [WebMethod]
            public static List<trafficSourceData> getTrafficSourceData(List<string> gData)
            {
                List<trafficSourceData> t = new List<trafficSourceData>();
                string[] arrColor = new string[] { "#231F20", "#FFC200", "#F44937", "#16F27E", "#FC9775", "#5A69A6" };
    
                string conn = ConfigurationManager.ConnectionStrings["EmployeeManagementConnectionString"].ConnectionString;
    
                using (SqlConnection cn = new SqlConnection(conn))
                {
                    string myQuery = "select * from traffic_data where year =@year ";
                    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;
            }
    

    Result:

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 29, 2018 3:17 AM
  • User283571144 posted

    Hi Ashraf007,

    When i look the same pie in chart.js page ... The Pie Chart look so beautiful and elegant ...

    See detail http://www.chartjs.org/samples/latest/charts/pie.html

    What reference i need to add to get the above look ...

    If you want to use newest chart.js, you should modify the chart function with passing new parameter to it.

    Details, you could refer to below article.

    http://www.chartjs.org/docs/latest/charts/doughnut.html 

    More details about the test demo, you could refer to below codes:

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js" type="text/javascript"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js" type="text/javascript"></script>
        <script>
            $(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: "PieChart.aspx/getTrafficSourceData",
                        data: jsonData,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: OnSuccess_,
                        error: OnErrorCall_
                    });
    
                    function OnSuccess_(response) {
                        var aData = response.d;
                        var dataarr = [];
                        var Labelarr = [];
                        var Colorarr = [];
                        $.each(aData, function (inx, val) {
                            dataarr.push(val.value);
                            Labelarr.push(val.label);
                            Colorarr.push(val.color);
                        });
                        var ctx = $("#myChart").get(0).getContext("2d");
                        var config = {
                            type: 'pie',
                            data: {
                                datasets: [{
                                    data: dataarr,
                                    backgroundColor: Colorarr,
                                }],
                                labels: Colorarr
                            },
                            options: {
                                responsive: true
                            }
                        };
                        var myPieChart = new Chart(ctx, config);
                    }
                    function OnErrorCall_(response) { }
                    e.preventDefault();
                });
    
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <select id="ddlyear">
                    <option>2010</option>
                    <option>2011</option>
                    <option>2012</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 />
                <div id="canvas-holder" style="width: 20%">
                    <canvas id="myChart" width="200" height="200"></canvas>
                </div>
            </div>
        </form>
    </body>
    </html>
    

    Result:

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 30, 2018 2:35 AM
  • User1152553138 posted

    Hi Ashraf007,

    Ashraf007

    When i look the same pie in chart.js page ... The Pie Chart look so beautiful and elegant ...

    See detail http://www.chartjs.org/samples/latest/charts/pie.html

    What reference i need to add to get the above look ...

    If you want to use newest chart.js, you should modify the chart function with passing new parameter to it.

    Details, you could refer to below article.

    http://www.chartjs.org/docs/latest/charts/doughnut.html 

    More details about the test demo, you could refer to below codes:

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js" type="text/javascript"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js" type="text/javascript"></script>
        <script>
            $(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: "PieChart.aspx/getTrafficSourceData",
                        data: jsonData,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: OnSuccess_,
                        error: OnErrorCall_
                    });
    
                    function OnSuccess_(response) {
                        var aData = response.d;
                        var dataarr = [];
                        var Labelarr = [];
                        var Colorarr = [];
                        $.each(aData, function (inx, val) {
                            dataarr.push(val.value);
                            Labelarr.push(val.label);
                            Colorarr.push(val.color);
                        });
                        var ctx = $("#myChart").get(0).getContext("2d");
                        var config = {
                            type: 'pie',
                            data: {
                                datasets: [{
                                    data: dataarr,
                                    backgroundColor: Colorarr,
                                }],
                                labels: Colorarr
                            },
                            options: {
                                responsive: true
                            }
                        };
                        var myPieChart = new Chart(ctx, config);
                    }
                    function OnErrorCall_(response) { }
                    e.preventDefault();
                });
    
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <select id="ddlyear">
                    <option>2010</option>
                    <option>2011</option>
                    <option>2012</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 />
                <div id="canvas-holder" style="width: 20%">
                    <canvas id="myChart" width="200" height="200"></canvas>
                </div>
            </div>
        </form>
    </body>
    </html>

    Result:

    Best Regards,

    Brando

    Thank you so much ... How to change the color of pie chart like this http://www.chartjs.org/samples/latest/charts/pie.html

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 30, 2018 7:34 AM

All replies

  • User475983607 posted

    Your script references are most likely incorrect and you're getting 404 (not found) error in the network tab.  Fix the file reference errors then continue with the tutorial.

    Friday, August 24, 2018 1:00 PM
  • User-1171043462 posted

    Complete working example with Source code for Chart.js

    Implement Free HTML5 Canvas charts using Chart.js in ASP.Net

    Implementing HTML5 Canvas Charts in ASP.Net MVC Razor

    Friday, August 24, 2018 1:51 PM
  • User1152553138 posted

    Thanks ... I just run the said below code ...

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <style type="text/css">
            body
            {
                font-family: Arial;
                font-size: 10pt;
            }
        </style>
    </head>
    <body>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        
        <script src="//cdn.jsdelivr.net/excanvas/r3/excanvas.js" type="text/javascript"></script>
        <script src="//cdn.jsdelivr.net/chart.js/0.2/Chart.js" type="text/javascript"></script>
    
    
        <form id="form1" runat="server">
        <script type="text/javascript">
            $(function () {
                LoadChart();
                $("[id*=ddlCountries]").bind("change", function () {
                    LoadChart();
                });
                $("[id*=rblChartType] input").bind("click", function () {
                    LoadChart();
                });
            });
            function LoadChart() {
                var chartType = parseInt($("[id*=rblChartType] input:checked").val());
                $.ajax({
                    type: "POST",
                    url: "CS.aspx/GetChart",
                    data: "{country: '" + $("[id*=ddlCountries]").val() + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        $("#dvChart").html("");
                        $("#dvLegend").html("");
                        var data = eval(r.d);
                        var el = document.createElement('canvas');
                        $("#dvChart")[0].appendChild(el);
    
                        //Fix for IE 8
                        if ($.browser.msie && $.browser.version == "8.0") {
                            G_vmlCanvasManager.initElement(el);
                        }
                        var ctx = el.getContext('2d');
                        var userStrengthsChart;
                        switch (chartType) {
                            case 1:
                                userStrengthsChart = new Chart(ctx).Pie(data);
                                break;
                            case 2:
                                userStrengthsChart = new Chart(ctx).Doughnut(data);
                                break;
                        }
                        for (var i = 0; i < data.length; i++) {
                            var div = $("<div />");
                            div.css("margin-bottom", "10px");
                            div.html("<span style = 'display:inline-block;height:10px;width:10px;background-color:" + data[i].color + "'></span> " + data[i].text);
                            $("#dvLegend").append(div);
                        }
                    },
                    failure: function (response) {
                        alert('There was an error.');
                    }
                });
            }
        </script>
        <table border="0" cellpadding="0" cellspacing="0">
            <tr>
                <td>
                    Country:
                    <asp:DropDownList ID="ddlCountries" runat="server">
                        <asp:ListItem Text="USA" Value="USA" />
                        <asp:ListItem Text="Germany" Value="Germany" />
                        <asp:ListItem Text="France" Value="France" />
                        <asp:ListItem Text="Brazil" Value="Brazil" />
                    </asp:DropDownList>
                    <asp:RadioButtonList ID="rblChartType" runat="server" RepeatDirection="Horizontal">
                        <asp:ListItem Text="Pie" Value="1" Selected="True" />
                        <asp:ListItem Text="Doughnut" Value="2" />
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr>
                <td>
                    <div id="dvChart">
                    </div>
                </td>
                <td>
                    <div id="dvLegend">
                    </div>
                </td>
            </tr>
        </table>
        </form>
    </body>
    </html>
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Text;
    using System.Web.Services;
    using System.Data.SqlClient;
    using System.Configuration;
    
    
    public partial class CS : System.Web.UI.Page
    {
    [WebMethod]
    public static string GetChart(string country)
    {
        string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = string.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", country);
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = query;
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("[");
                    while (sdr.Read())
                    {
                        sb.Append("{");
                        System.Threading.Thread.Sleep(50);
                        string color = String.Format("#{0:X6}", new Random().Next(0x1000000)); 
                        sb.Append(string.Format("text :'{0}', value:{1}, color: '{2}'", sdr[0], sdr[1], color));
                        sb.Append("},");
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                    sb.Append("]");
                    con.Close();
                    return sb.ToString();
                }
            }
        }
    }
    }

    Now i would like to change chart.js reference with the latest once from here. https://cdnjs.com/libraries/Chart.js

    What reference i need to add from the above link for fresh new chart look?

    Saturday, August 25, 2018 3:44 AM
  • User1152553138 posted

    I have just changed the chart with latest reference and got the below error ...

    This reference add
    
    
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        
        <script src="//cdn.jsdelivr.net/excanvas/r3/excanvas.js" type="text/javascript"></script>
    
     <%--   <script src="//cdn.jsdelivr.net/chart.js/0.2/Chart.js" type="text/javascript"></script>--%>
    
        <script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js" type="text/javascript"></script>

    Error Pie is not a function ... Error screen shot link https://ibb.co/igaQtU

    Saturday, August 25, 2018 3:52 AM
  • User1152553138 posted

    Okay ... i have done the changes and its working fine ... See below ...

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
      
      <form id="form1" runat="server">
      
      
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js" type="text/javascript"></script>
      <script src="jquery-2.1.4.min.js" type="text/javascript"></script>
    
    
     <asp:Panel ID="asppanel" runat="server" width="600px" height="500px"> 
     
     <canvas id="myChart" ></canvas>
     
     </asp:Panel>
    
    <script type="text/javascript">
        var ctx = document.getElementById("myChart").getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
                datasets: [{
                    label: '# of Votes',
                    data: [100, 150, 300, 500, 200, 300],
                    backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                    borderColor: [
                    'rgba(255,99,132,1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        });
    </script>
    
    
        </form>
    </body>
    </html>
    
    Static Chart Code ...

    Now i would like to generate it dynamically from database just like how mudassir khan as done https://www.aspsnippets.com/Articles/Implement-Free-HTML5-Canvas-charts-using-Chartjs-in-ASPNet.aspx

    Saturday, August 25, 2018 6:08 AM
  • User475983607 posted

    Now i would like to generate it dynamically from database just like how mudassir khan as

    There's no magic.  Simply either render the JavaScript on the server rather than hard coded on the client as you are doing now or return JSON from an AJAX call. 

    Here is a basic example.

    https://forums.asp.net/p/2129509/6169081.aspx

    This task requires a fundamental understanding of Javascript, C# types, and JSON.   There are plenty of examples in the Internet.

    Post you code if you run into trouble.

    Saturday, August 25, 2018 10:41 AM
  • User1152553138 posted

    Thanks you all ... As per your suggestion i tried the below method ... The chart is not rendering ....

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head runat="server">
        <title></title>
    </head>
    
    <body>
    
        <form id="form1" runat="server">
       
      
        <script src="js/Chart.js" type="text/javascript"></script>
        <script src="js/jquery-2.1.4.min.js" type="text/javascript"></script>
    
    
       <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/>
    
    <script type="text/javascript">
    
        $(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: "Deafult.aspx/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();
            });
        });
    
    </script>
    
    
    <canvas id="myChart" width="200" height="200"></canvas>
    
        </form>
    </body>
    </html>
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Text;
    using System.Web.Services;
    using System.Data.SqlClient;
    using System.Configuration;
    
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        public class trafficSourceData
        {
            public string label { get; set; }
            public string value { get; set; }
            public string color { get; set; }
            public string hightlight { get; set; }
        }
    
        [WebMethod]
    
        public List<trafficSourceData> getTrafficSourceData(List<string> gData)
        {
            List<trafficSourceData> t = new List<trafficSourceData>();
            string[] arrColor = new string[] { "#231F20", "#FFC200", "#F44937", "#16F27E", "#FC9775", "#5A69A6" };
    
            string conn = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    
            using (SqlConnection cn = new SqlConnection(conn))
            {
                string myQuery = "select * from traffic_data where YEAR =@year ";
                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;
        }
    
    
    }

    <a href="https://ibb.co/mv2J09"><img src="https://thumb.ibb.co/mv2J09/Error.png" alt="Error" border="0"></a>

    Error Image Link https://ibb.co/mv2J09

    Kindly help me in this ...

    Monday, August 27, 2018 9:37 AM
  • User283571144 posted

    Hi Ashraf007,

    Thanks you all ... As per your suggestion i tried the below method ... The chart is not rendering ....

    According to your description and code,I suggest you could add static for the webmethod in code-behind and add # before id to locate the  btnGeneratePieChart button in js code.

    For more details, you could refer to the code below.

    .aspx

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js" type="text/javascript"></script>
        <script>
            $(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: "PieChart.aspx/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);
                        });
                        console.log(arr);
                        var ctx = $("#myChart").get(0).getContext("2d");
                        var myPieChart = new Chart(ctx).Pie(arr);
                    }
    
                    function OnErrorCall_(response) { }
                    e.preventDefault();
                });
    
            });
    
    
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <select id="ddlyear">
                    <option>2010</option>
                    <option>2011</option>
                    <option>2012</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>
            </div>
        </form>
    </body>
    </html>
    

    Code-behind:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Text;
    using System.Web.Services;
    using System.Data.SqlClient;
    using System.Configuration;
    public class trafficSourceData
            {
                public string label { get; set; }
                public string value { get; set; }
                public string color { get; set; }
                public string hightlight { get; set; }
            }
    
            [WebMethod]
            public static List<trafficSourceData> getTrafficSourceData(List<string> gData)
            {
                List<trafficSourceData> t = new List<trafficSourceData>();
                string[] arrColor = new string[] { "#231F20", "#FFC200", "#F44937", "#16F27E", "#FC9775", "#5A69A6" };
    
                string conn = ConfigurationManager.ConnectionStrings["EmployeeManagementConnectionString"].ConnectionString;
    
                using (SqlConnection cn = new SqlConnection(conn))
                {
                    string myQuery = "select * from traffic_data where year =@year ";
                    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;
            }
    

    Result:

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 29, 2018 3:17 AM
  • User1152553138 posted

    Hi Ashraf007,

    Ashraf007

    Thanks you all ... As per your suggestion i tried the below method ... The chart is not rendering ....

    According to your description and code,I suggest you could add static for the webmethod in code-behind and add # before id to locate the  btnGeneratePieChart button in js code.

    For more details, you could refer to the code below.

    .aspx

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js" type="text/javascript"></script>
        <script>
            $(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: "PieChart.aspx/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);
                        });
                        console.log(arr);
                        var ctx = $("#myChart").get(0).getContext("2d");
                        var myPieChart = new Chart(ctx).Pie(arr);
                    }
    
                    function OnErrorCall_(response) { }
                    e.preventDefault();
                });
    
            });
    
    
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <select id="ddlyear">
                    <option>2010</option>
                    <option>2011</option>
                    <option>2012</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>
            </div>
        </form>
    </body>
    </html>

    Code-behind:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Text;
    using System.Web.Services;
    using System.Data.SqlClient;
    using System.Configuration;
    public class trafficSourceData
            {
                public string label { get; set; }
                public string value { get; set; }
                public string color { get; set; }
                public string hightlight { get; set; }
            }
    
            [WebMethod]
            public static List<trafficSourceData> getTrafficSourceData(List<string> gData)
            {
                List<trafficSourceData> t = new List<trafficSourceData>();
                string[] arrColor = new string[] { "#231F20", "#FFC200", "#F44937", "#16F27E", "#FC9775", "#5A69A6" };
    
                string conn = ConfigurationManager.ConnectionStrings["EmployeeManagementConnectionString"].ConnectionString;
    
                using (SqlConnection cn = new SqlConnection(conn))
                {
                    string myQuery = "select * from traffic_data where year =@year ";
                    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;
            }

    Result:

    Best Regards,

    Brando

    Thanks ...

    May i know whether this is the latest chart.js reference detail ...

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js" type="text/javascript"></script>

    When i look the same pie in chart.js page ... The Pie Chart look so beautiful and elegant ...

    See detail http://www.chartjs.org/samples/latest/charts/pie.html

    What reference i need to add to get the above look ...

    Wednesday, August 29, 2018 4:16 AM
  • User283571144 posted

    Hi Ashraf007,

    When i look the same pie in chart.js page ... The Pie Chart look so beautiful and elegant ...

    See detail http://www.chartjs.org/samples/latest/charts/pie.html

    What reference i need to add to get the above look ...

    If you want to use newest chart.js, you should modify the chart function with passing new parameter to it.

    Details, you could refer to below article.

    http://www.chartjs.org/docs/latest/charts/doughnut.html 

    More details about the test demo, you could refer to below codes:

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js" type="text/javascript"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js" type="text/javascript"></script>
        <script>
            $(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: "PieChart.aspx/getTrafficSourceData",
                        data: jsonData,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: OnSuccess_,
                        error: OnErrorCall_
                    });
    
                    function OnSuccess_(response) {
                        var aData = response.d;
                        var dataarr = [];
                        var Labelarr = [];
                        var Colorarr = [];
                        $.each(aData, function (inx, val) {
                            dataarr.push(val.value);
                            Labelarr.push(val.label);
                            Colorarr.push(val.color);
                        });
                        var ctx = $("#myChart").get(0).getContext("2d");
                        var config = {
                            type: 'pie',
                            data: {
                                datasets: [{
                                    data: dataarr,
                                    backgroundColor: Colorarr,
                                }],
                                labels: Colorarr
                            },
                            options: {
                                responsive: true
                            }
                        };
                        var myPieChart = new Chart(ctx, config);
                    }
                    function OnErrorCall_(response) { }
                    e.preventDefault();
                });
    
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <select id="ddlyear">
                    <option>2010</option>
                    <option>2011</option>
                    <option>2012</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 />
                <div id="canvas-holder" style="width: 20%">
                    <canvas id="myChart" width="200" height="200"></canvas>
                </div>
            </div>
        </form>
    </body>
    </html>
    

    Result:

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 30, 2018 2:35 AM
  • User1152553138 posted

    Hi Ashraf007,

    Ashraf007

    When i look the same pie in chart.js page ... The Pie Chart look so beautiful and elegant ...

    See detail http://www.chartjs.org/samples/latest/charts/pie.html

    What reference i need to add to get the above look ...

    If you want to use newest chart.js, you should modify the chart function with passing new parameter to it.

    Details, you could refer to below article.

    http://www.chartjs.org/docs/latest/charts/doughnut.html 

    More details about the test demo, you could refer to below codes:

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js" type="text/javascript"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js" type="text/javascript"></script>
        <script>
            $(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: "PieChart.aspx/getTrafficSourceData",
                        data: jsonData,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: OnSuccess_,
                        error: OnErrorCall_
                    });
    
                    function OnSuccess_(response) {
                        var aData = response.d;
                        var dataarr = [];
                        var Labelarr = [];
                        var Colorarr = [];
                        $.each(aData, function (inx, val) {
                            dataarr.push(val.value);
                            Labelarr.push(val.label);
                            Colorarr.push(val.color);
                        });
                        var ctx = $("#myChart").get(0).getContext("2d");
                        var config = {
                            type: 'pie',
                            data: {
                                datasets: [{
                                    data: dataarr,
                                    backgroundColor: Colorarr,
                                }],
                                labels: Colorarr
                            },
                            options: {
                                responsive: true
                            }
                        };
                        var myPieChart = new Chart(ctx, config);
                    }
                    function OnErrorCall_(response) { }
                    e.preventDefault();
                });
    
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <select id="ddlyear">
                    <option>2010</option>
                    <option>2011</option>
                    <option>2012</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 />
                <div id="canvas-holder" style="width: 20%">
                    <canvas id="myChart" width="200" height="200"></canvas>
                </div>
            </div>
        </form>
    </body>
    </html>

    Result:

    Best Regards,

    Brando

    Thank you so much ... How to change the color of pie chart like this http://www.chartjs.org/samples/latest/charts/pie.html

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 30, 2018 7:34 AM
  • User283571144 posted

    Hi Ashraf007,

    Since this question is not related with the thread title, I suggest you could start a new thread.

    This will help other people who faces the same issue search for the answer more easily.

    Best Regards,

    Brando

    Thursday, August 30, 2018 8:42 AM