locked
Asp.net webform Chart.js RRS feed

  • Question

  • User-47589850 posted
    Hi,
    I want to use chartjs v2 on asp.net webform. I can create webmethod json data. But i cant bind chart.js dataset. I'm searched samples but either sample asp.net mvc or chart.js v1.
    Can you share full sample code for chartjs v2 .net webform?
    Thanks in advance
    Monday, July 23, 2018 8:56 PM

All replies

  • User475983607 posted

    asp.netlearning

    I want to use chartjs v2 on asp.net webform. I can create webmethod json data. But i cant bind chart.js dataset. I'm searched samples but either sample asp.net mvc or chart.js v1.
    Can you share full sample code for chartjs v2 .net webform?

    There's not difference between invoking an MVC action or a Web Method from the client perspective.  Post the source code so we can see what you are doing.

    Monday, July 23, 2018 10:50 PM
  • User36583972 posted


    Hi Friend,

    I want to use chartjs v2 on asp.net webform. I can create webmethod json data. But i cant bind chart.js dataset. I'm searched samples but either sample asp.net mvc or chart.js v1.
    Can you share full sample code for chartjs v2 .net webform?

    The following sample for your reference.

    ASPX:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.min.js"></script>
        <script src="Scripts/jquery-3.3.1.min.js"></script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <canvas id="bar-chart" width="800" height="450"></canvas>
                <script type="text/javascript">
                    var data = {};
                    data.Code = "123456";
                    data.Lname = "testlname";
                    $.ajax({
                        type: 'POST',
                        url: 'Chartjsdemo.aspx/ChartjsTempData',
                        data: '{data:' + JSON.stringify(data) + '}',
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        success: function (r) {
                            var da = r.d;
                            var dataStrArr=da.split(",")
                            var dataIntArr = [];
                            dataStrArr.forEach(function (data, index, arr) {
                                dataIntArr.push(+data);
                            });
    
                            new Chart(document.getElementById("bar-chart"), {
                                type: 'bar',
                                data: {
                                    labels: ["Africa", "Asia", "Europe", "Latin America", "North America"],
                                    datasets: [
                                        {
                                            label: "Population (millions)",
                                            backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850"],
                                            data: dataIntArr
                                        }
                                    ]
                                },
                                options: {
                                    legend: { display: false },
                                    title: {
                                        display: true,
                                        text: 'Predicted world population (millions) in 2050'
                                    }
                                }
                            });
                        }
                    });
                </script>
            </div>
        </form>
    </body>
    </html>
    

    ASPX.CS:

            [WebMethod]
            [ScriptMethod]
            public static string ChartjsTempData(Data data)
            {
                return "2478, 5267, 734, 784, 433";
    
            }

    Best Regards,

    Yong Lu

    Tuesday, July 24, 2018 7:18 AM
  • User-47589850 posted

    Hi,

    Of course I'll share source code. I think bug jquery json code. 

    .cs

     [WebMethod]
            [ScriptMethod(UseHttpGet = true)]
            public static string GetChart()
            {
                SqlCommand cmd = new SqlCommand("SELECT      Teknisyen.Teknisyen_Adi, COUNT(OnarimID) AS ProjeSayisi, CONVERT(DECIMAL(5, 1), (COUNT(TeknisyenID) * 100.0) / (SELECT COUNT(*) FROM Onarim)) AS Yuzde FROM Onarim      INNER JOIN                          dbo.Teknisyen ON dbo.Teknisyen.Teknik_ID = dbo.Onarim.TeknisyenID GROUP BY  TeknisyenID,Teknisyen_Adi ORDER BY ProjeSayisi DESC", baglan.baglan());
               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("]");
                return sb.ToString();
            }
                   

    webform

    <div style="width: 100%; height: 100%">
    <canvas id="myChart" style="padding: 0; margin: auto; display: block;"></canvas>
    </div>

    .js

    <script src="/plugins/jquery.min.js"></script>

    <script src="/plugins/chart.js/chart.min.js"></script>

    <script type="text/javascript">
    $(document).ready(function () {

    $.ajax({
    type: "GET",
    url: "/Admin/admin-index.aspx/GetChart",

    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnSuccess_
    });

    function OnSuccess_(response) {
    var dataTotal = [];

    $.each(response, function (i, obj) {
    var data = {};

    data.value = parseInt(obj.value);
    data.color = obj.color;

    dataTotal.push(data);
    });
    var ctx = $("#myChart").get(0).getContext("2d");
    var myNewChart = new Chart(ctx, {
    type: 'bar',
    data: {
    labels: ["Red", "Blue"],
    datasets: [{
    label: '# of Votes',
    data: data.value,
    backgroundColor: [
    'rgba(255, 99, 132, 0.2)',
    'rgba(54, 162, 235, 0.2)',

    ],
    borderColor: [
    'rgba(255,99,132,1)',
    'rgba(54, 162, 235, 1)',

    ],
    borderWidth: 1
    }]
    },
    options: {
    scales: {
    yAxes: [{
    ticks: {
    beginAtZero: true
    }
    }]
    }
    }
    });

    }
    });


    </script>

    Tuesday, July 24, 2018 8:30 AM
  • User-47589850 posted

    Hi, 

    I'm trying code. But dataIntArr return nan,nan . I couldnt not databind. 

    Do you have sample code with data from database ?

    Thanks

    Tuesday, July 24, 2018 9:00 AM
  • User-47589850 posted

    Hi again,

    jquery success function return

    function OnSuccess_(r) {
    var da = r.d;

    1. d:"[{text :'Test1', value:2, color: '#D0C3C4'},{text :'Test2', value:1, color: '#5E960A'}]
    Tuesday, July 24, 2018 9:55 AM
  • User475983607 posted

    You're going about this the wrong way.  Web Methods return types.  There is no good reason to build a JSON string by hand.  Simply craft a type, populate the type, return the type to the AJAX function update the chart source.

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

    If you do a search for chart.js on these forums, you'll find a lot of example.

    Tuesday, July 24, 2018 10:50 AM
  • User-47589850 posted

    Hi,

    Do you have sample code for webforms? 

    Thanks

    Tuesday, July 24, 2018 1:36 PM
  • User-1171043462 posted

    Refer

    Complete example using Chart.js available here

    Create and display Bar Chart in ASP.Net using HTML5, JSON and jQuery

    Tuesday, July 24, 2018 1:44 PM
  • User-47589850 posted

    Hi,

    Thanks for code. I followed your web sites. I even saw the first example. 

    But your code for chartjs v1. And v1 havent animation etc. Im searching for v2

    Tuesday, July 24, 2018 2:18 PM
  • User475983607 posted

    Hi,

    Thanks for code. I followed your web sites. I even saw the first example. 

    But your code for chartjs v1. And v1 havent animation etc. Im searching for v2

    It's irrelevant.   The concept does not change.  Do an AJAX request to get JSON data and assigning the data to the chart API.  The data format must match the openly published chart.js documentation.  

    Tuesday, July 24, 2018 2:25 PM