Click here to Skip to main content
15,896,359 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
//Default.aspx
<div class="card-body">
                                       <div class="chart-area">
                                           <canvas id="myAreaChart"></canvas>
                                       </div>
                                   </div>




//chart-area.js
var ctx = document.getElementById("myAreaChart");
var myLineChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    datasets: [{
      label: "Earnings",
      lineTension: 0.3,
      backgroundColor: "rgba(78, 115, 223, 0.05)",
      borderColor: "rgba(78, 115, 223, 1)",
      pointRadius: 3,
      pointBackgroundColor: "rgba(78, 115, 223, 1)",
      pointBorderColor: "rgba(78, 115, 223, 1)",
      pointHoverRadius: 3,
      pointHoverBackgroundColor: "rgba(78, 115, 223, 1)",
      pointHoverBorderColor: "rgba(78, 115, 223, 1)",
      pointHitRadius: 10,
      pointBorderWidth: 2,
      data: [0, 10000],
    }],
  },
  options: {
    maintainAspectRatio: false,
    layout: {
      padding: {
        left: 10,
        right: 25,
        top: 25,
        bottom: 0
      }
    },
    scales: {
      xAxes: [{
        time: {
          unit: 'date'
        },
        gridLines: {
          display: false,
          drawBorder: false
        },
        ticks: {
          maxTicksLimit: 7
        }
      }],
      yAxes: [{
        ticks: {
          maxTicksLimit: 5,
          padding: 10,
          // Include a dollar sign in the ticks
          callback: function(value, index, values) {
            return '$' + number_format(value);
          }
        },
        gridLines: {
          color: "rgb(234, 236, 244)",
          zeroLineColor: "rgb(234, 236, 244)",
          drawBorder: false,
          borderDash: [2],
          zeroLineBorderDash: [2]
        }
      }],
    },
    legend: {
      display: false
    },
    tooltips: {
      backgroundColor: "rgb(255,255,255)",
      bodyFontColor: "#858796",
      titleMarginBottom: 10,
      titleFontColor: '#6e707e',
      titleFontSize: 14,
      borderColor: '#dddfeb',
      borderWidth: 1,
      xPadding: 15,
      yPadding: 15,
      displayColors: false,
      intersect: false,
      mode: 'index',
      caretPadding: 10,
      callbacks: {
        label: function(tooltipItem, chart) {
          var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || '';
          return datasetLabel + ': $' + number_format(tooltipItem.yLabel);
        }
      }
    }
  }


What I have tried:

I don't want to use data given in chart-area.js. It should give output from database MS SQL. I have tried to insert in default.aspx.cs like below but it gives data from chart-area.js.

//Default.aspx.cs

public partial class Default : System.Web.UI.Page
   {
       protected void Page_Load(object sender, EventArgs e)
       {

       }

       [WebMethod]
       public static string GetAllRecords()
       {
           DataTable dt = new DataTable();
           using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["db"].ConnectionString))
           {
               using (SqlCommand cmd = new SqlCommand("SELECT MONTH(OrderDate), COUNT(Products) AS Products FROM tblOrderProducts GROUP BY OrderDate", con))
               {
                   con.Open();
                   SqlDataAdapter da = new SqlDataAdapter(cmd);
                   da.Fill(dt);
                   JavaScriptSerializer serializer = new JavaScriptSerializer();
                   List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                   Dictionary<string, object> row;
                   foreach (DataRow dr in dt.Rows)
                   {
                       row = new Dictionary<string, object>();
                       foreach (DataColumn col in dt.Columns)
                       {
                           row.Add(col.ColumnName, dr[col]);
                       }
                       rows.Add(row);
                   }

                   return serializer.Serialize(rows);
               }
           }
       }
   }
Posted
Updated 4-Apr-21 23:43pm

1 solution

C#
public List<Records>GetAllRecords()
 {
   List<Records> ListRecords = new List<Records>();

// Fetch data from db through the query


 // Use this for loop to construct List instead of your foreach loop

    for (int i = 0; i < dt.Rows.Count; i++)
            {                               
                Records oRec = new Records();
                oRec.Month = !string.IsNullOrEmpty(Convert.ToString(dt.Rows[i]["Month"])) ? Convert.ToString(dt.Rows[i]["Month"]) : "";              
                oRec.Count= !string.IsNullOrEmpty(Convert.ToString(dt.Rows[i]["Count"])) ? Convert.ToInt32(dt.Rows[i]["Count"]) : 0;

                ListRecords.Add(oRec);
            }
           
            return ListRecords;
               }
           }
       }

    public class Records
    {
      
        public string Month { get; set; }     
        public int Count { get; set; }
       
    }


add below script and html code in your default.aspx

<div id="curve_chart"></div>

JavaScript
<script type="text/javascript">
    google.charts.load('current', { 'packages': ['corechart'] });
</script>

<script type="text/javascript">

        
      var chartData = [];       
        GetAllRecords();   

        function GetAllRecords() {
            chartData = [];
       
            $.ajax({
                url: 'GetAllRecords',   //  path to your function
                contentType: "application/json; charset=utf-8",
                async: false,
                cache: false,
                data: obj,
                success: function (data) {
                   var resultData = data.ListRecords;               
               

                    var length = resultData.length;
                    $.each(resultData, function (index, value) {                      
                       chartData.push([value.Month, value.Count]);
                        if (index === (length - 1)) {
                            google.charts.setOnLoadCallback(drawChart);
                        }
                    });                     
                }
            });
        }

        function drawChart() {
           
            var data = new google.visualization.DataTable();             
            data.addColumn('string', 'Month');
            data.addColumn('number', 'Count');            
              
            data.addRows(chartData);

            var options = {             
                title: 'Monthwise Products count',
                pointsVisible: true,              
                legend: {position: 'none'},
                titleTextStyle: {
                    color: '#01579b',
                    fontSize: 30,
                    fontName: 'Arial',
                    bold: true,
                    italic: true
                },

                hAxis: {
                                
                    showTextEvery: 1,
                    slantedText: true,
                    slantedTextAngle: 60,
                    gridlines: { count: chartData.length }
                },
                vAxis: {
                    title: "",                    
                    minValue: 0,
                   // format: '',

                }
            };
         
            var chart = new google.visualization.AreaChart(document.getElementById('curve_chart'));
            chart.draw(data, options);
            
        }

</script>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900