json obj从asp.net mvc到canvas.js图表

时间:2017-12-21 19:03:10

标签: javascript json asp.net-mvc object canvas

我在类似的帖子中搜索过,但找不到解决方案!! 在我的asp.net mvc控制器中,我有一个方法:public object OfferChart()

List<Det> obj = new List<Det>();

            foreach (DataRow dro in dt.Rows)
            {
                Det def = new Det();
                def.xval = Convert.ToString(dro["Section"]);
                def.yval = Convert.ToDecimal(dro["Percent"]);
                obj.Add(def);
            }
            return Json(obj, JsonRequestBehavior.AllowGet);

我想要的是从jj对象中的obj发送日期,并使用它代替我的图表(画布)的dataPoints:

function chartOfferSections() {

var chart = new CanvasJS.Chart("chartOfferSections", {
            theme: "light2", // "light1", "light2", "dark1", "dark2"
            exportEnabled: true,
            animationEnabled: true,
            title: {
                text: "Oferte pe sectoare"
            },
            data: [{
                type: "pie",
                startAngle: 25,
                toolTipContent: "<b>{label}</b>: {y}%",
                showInLegend: "true",
                legendText: "{label}",
                indexLabelFontSize: 16,
                indexLabel: "{label} - {y}%",
                dataPoints: 
                [
                    { y: 25.00, label: "Sectorul 1" },
                    { y: 25.00, label: "Sectorul 2" },
                    { y: 25.00, label: "Sectorul 3" },
                    { y: 25.00, label: "Sectorul 4" }
                ]
            }]
        });
        chart.render();
}

查找一些示例并尝试实现,但没有工作

var dataPts[];
$.ajax({
    cache: false,
    async: false,
    type: "POST",
    dataType: "Json",
    contentType: "application/json; charset=utf-8",
    url: '@Url.Action("OfferChart")',
    data: obj,
    success: function (data) {
        var len = data.d.length;
        for (var i = 0; i < len; i++) {
            dataPts.push({
                label: data.d[i].xval,
                y: data.d[i].yval
            });
        }

1 个答案:

答案 0 :(得分:0)

在成功功能结束时,您需要将临时数据分配给图表选项,如此

chart.options.data[0].dataPoints = dataPts

然后致电chart.render();