Create Charts with Chart.js Using C# string causes

2020-08-01 08:34发布

I am trying to create charts using Chart Js in my asp.net application. I am fetching data from code database and and generating the string as per the documentation in back end. And then i am calling that web method to fetch the chart data and render it on page.

 function LoadVarianceChart() {
        var data;
        $.ajax({
            type: "POST",
            url: "Analysis.aspx/GetVarianceChart",
            data: "",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                $("#dvVarianceChart").html("");
                var obj = r.d;
                console.log(obj);
                data = obj;

                var el = document.createElement('canvas');
                $("#dvVarianceChart")[0].appendChild(el);

                //Fix for IE 8
                if ($.browser.msie && $.browser.version == "8.0") {
                    G_vmlCanvasManager.initElement(el);
                }
                var ctx = el.getContext('2d');
                ctx.canvas.width = 300;
                ctx.canvas.height = 300;
                var userStrengthsChart;
                userStrengthsChart = new Chart(ctx).Bar(data);
            },
            failure: function (response) {
                alert('There was an error.');
            }
        });
    }

Here is my c# web method.

     [WebMethod]
    public static string GetVarianceChart()
    {
        DataSet ds = Utility.ExecuteDataTable("GetAdvarienceByBrandFamily", null);
        VarianceChartModel bar = new VarianceChartModel();

        bar.labels = ds.Tables[0].Rows[0][0].ToString().Split(',');
        bar.datasets = new List<datasets>();

        for (int i = 1; i < ds.Tables.Count; i++)
        {
            datasets dataset = new datasets();
            dataset.data = Array.ConvertAll(ds.Tables[i].Rows[0][0].ToString().Split(','), decimal.Parse);
            dataset.label = "new";
            dataset.fillColor = "rgba(220,220,220,0.5)";
            dataset.highlightFill = "rgba(220,220,220,0.75)";
            dataset.highlightStroke = "rgba(220,220,220,1)";
            dataset.strokeColor = "rgba(220,220,220,0.8)";
            bar.datasets.Add(dataset);
        }

        var serializer = new JsonSerializer();
        var stringWriter = new StringWriter();
        var writer = new JsonTextWriter(stringWriter);
        writer.QuoteName = false;
        serializer.Serialize(writer, bar);
        writer.Close();
        var json = stringWriter.ToString();
        return json.ToString();
    }
}

Here my web method is generating the string correctly as per the documentation. If i use the generated string statically in chart js then the chart is getting generated correctly. But when i try to provide the same string by calling the back end method then it gives me Uncaught TypeError: Cannot read property 'length' of undefined

I am not sure why it is behaving like this for the same string. Is this something related to C# string and java script string compatibility ?

2条回答
做个烂人
2楼-- · 2020-08-01 08:55

I figured out this problem. Here is the code which lets you create a chart by getting data from database using asp.net.

function LoadChart1() {
        var data;
        $.ajax({
            type: "POST",
            url: "Analysis.aspx/GetChart1",
            data: "{account: '" + $("[id*=ddlAccount]").val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                $("#dvChart").html("");
                $("#dvLegend").html("");
                var obj = r.d;
                data = JSON.parse(obj);

                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');
                ctx.canvas.width = 500;
                ctx.canvas.height = 500;
                var userStrengthsChart;
                userStrengthsChart = new Chart(ctx).Bar(data);
            },
            failure: function (response) {
                alert('There was an error.');
            }
        });
    }

Here is the web method which provides data to charts.

[WebMethod]
    public static string GetChart1(string account)
    {
        SqlParameter[] param = new SqlParameter[] { new SqlParameter("@account", account) };
        DataSet ds = Utility.ExecuteDataTable("GetChart1", param);
        if (ds.Tables[0].Rows.Count != 0)
        {
            VarianceChartModel bar = new VarianceChartModel();
            bar.labels = ds.Tables[0].Rows[0][0].ToString().Split(',');
            bar.datasets = new List<datasets>();

            for (int i = 1; i < ds.Tables.Count; i++)
            {
                string data = ds.Tables[i].Rows[0][0].ToString();
                if (!string.IsNullOrEmpty(data))
                {
                    datasets dataset = new datasets();
                    dataset.data = Array.ConvertAll(data.Split(','), decimal.Parse);
                    dataset.label = "new";
                    dataset.fillColor = "rgba(255, 102, 0,0.5)";
                    dataset.highlightFill = "rgba(255, 102, 0,0.75)";
                    dataset.highlightStroke = "rgba(255, 102, 0,0.50)";
                    dataset.strokeColor = "rgba(255, 102, 0,0.8)";
                    bar.datasets.Add(dataset);
                }
            }

            var serializer = new JsonSerializer();
            var stringWriter = new StringWriter();
            var writer = new JsonTextWriter(stringWriter);
            // writer.QuoteName = false;
            serializer.Serialize(writer, bar);
            writer.Close();
            var json = stringWriter.ToString();
            return json.ToString();
        }
        else
        {
            return null;
        }
    }
查看更多
迷人小祖宗
3楼-- · 2020-08-01 09:00
Here is the code it worked for me.For the bar chat
 <script type="text/javascript">
            var getchartdata = function () {
                debugger;
                var obj = {};
                obj.datefromt = $.trim($("[id*=txtfrom]").val());
                obj.datetot = $.trim($("[id*=txtto]").val());
                //obj.costtype = document.getElementById('drpcostytpe').value;
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "PublisherPayoutJschat.aspx/GetDataonclick",
                    data: JSON.stringify(obj),
                    async: true,
                    cache: false,
                    dataType: "json",
                    success: OnSuccess_,
                    error: OnErrorCall_
                })
                function OnSuccess_(reponse) {
                    var aData = reponse.d;
                    var aLabels = aData[0];
                    var aDatasets1 = aData[1];
                    var aDatasets2 = aData[2];
                    var barChartData = {
                        labels: aLabels,
                        datasets: [
                            {
                                label: "Date",
                                //fill:false,
                                fillColor: "#006495",
                                strokeColor: "rgba(220,220,220,1)",
                                pointColor: "rgba(200,122,20,1)",
                                data: aDatasets1
                            },
                            {
                                label: "Topup",
                                fillColor: "#004C70",
                                strokeColor: 'rgba(220,180,0,1)',
                                pointColor: 'rgba(220,180,0,1)',
                                data: aDatasets2
                            },

                        ]
                    }
                    var helpers = Chart.helpers;
                    var canvas = document.getElementById('chart_div');
                    var bar = new Chart(canvas.getContext('2d')).Bar(barChartData, {
                        responsive: false,
                        maintainAspectRatio: true,
                        animation: false
                    });
                    // 
                    document.getElementById('legend').innerHTML = "";
                    var legendHolder = document.createElement('div');
                    legendHolder.innerHTML = bar.generateLegend();
  document.getElementById('legend').appendChild(legendHolder.firstChild);
                }
                function OnErrorCall_(repo) {
                    alert(repo);
                }
            }
             </script>

---cs file
//GetDatachat for chart search data
        [WebMethod]
    public static List<object> GetDataonclick(string datefromt, string datetot)
        {
            string publisherid = "2000021";
            DataTable dt = new DataTable();

            List<object> iData = new List<object>();
            PublisherJavascriptDAL objpayout = new PublisherJavascriptDAL();
            dt = objpayout.Getbarchatpayout(publisherid, datefromt, datetot);
     string[] columnNames = dt.Columns.Cast<DataColumn>                        ().Select(x=>x.ColumnName).ToArray();
            Array.Reverse(columnNames);
            foreach (string dc in columnNames)
            {
                List<string> labels = new List<string>();
                List<double> lst_dataItem_1 = new List<double>();
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    if (dc == "TXdatetime")
                    {
                        labels.Add(dt.Rows[j]["TXdatetime"].ToString());
                        //iData.Add(labels);
                    }
                    else
                    {
                        lst_dataItem_1.Add(Convert.ToDouble(dt.Rows[j][dc].ToString()));
                    }
                }
                if (dc == "TXdatetime")
                    iData.Add(labels);
                else
                    iData.Add(lst_dataItem_1);

            }

            return iData;
        }
查看更多
登录 后发表回答