【问题标题】:CanvasJS Load Data Dynamically MVC RazorCanvasJS 动态加载数据 MVC Razor
【发布时间】:2021-03-22 11:42:13
【问题描述】:

我正在使用 asp.net core MVC 为我的应用程序创建动态图表。我正在使用 CanvasJS 来绘制图表。

我想根据屏幕上选择的参数绘制图表数据。因此,我有一个下拉列表和一个数据表,用于定义从数据库中检索哪些数据。

问题是点击UpdateChart按钮后我的图表没有加载。但是,当我调试应用程序并根据控制台日志时,js 函数正在运行,但它不会更新图表内的data

我的观点是这样的

<script>
   var chart;
   function myFunction() {
       console.log("Inside My Function_1");
       chart = new CanvasJS.Chart("chart-container", {
           zoomEnabled: true,
           title: {
               text: '@Html.Raw(ViewBag.ChartText)'//"My Text"
           },
           axisX: {
               title: "chart updates every 2 secs",
               crosshair: {
                   enabled: true,
                   snapToDataPoint: true
               }
           },
           axisY: {
               crosshair: {
                   enabled: true,
                   snapToDataPoint: true,
                   valueFormatString: "#,##0"
               }
           },
           toolTip: {
               shared: true
           },
           legend: {
               dockInsidePlotArea: true,
               verticalAlign: "top",
               horizontalAlign: "right"
           },
           data: [ @Html.Raw(ViewBag.AllData) ]
   });
       console.log("Inside My Function_2");
       chart.render();
       console.log("Inside My Function_3");

       }
   window.onload = myFunction;


   function GetData() {
       var table = $('#dataTable').DataTable();
       var data = table.$('input[type="checkbox"]').serializeArray();
       $.ajax({
           type: "POST",
           url: '@Url.Action("UpdateChart","Home")', //"/Home/UpdateChart",
           contentType: "application/x-www-form-urlencoded",
           data: data,
           dataType: "html",
           success: function (result) {
               console.log("Container remove called.");
               chart.destroy();
               //$('#chart-container').remove();
               //console.log("Container removed called.");
               //$('#graph-container').append('<div id="chart-container" class="chart-area-big"><div>');
               //console.log("Container appened again.");

               myFunction();
               console.log(result);
           }
       });
   }

</script>

       <div id="graph-container" class="card shadow mb-4">
           <div class="d-block card-header py-3">
               <h6 class="m-0 font-weight-bold text-primary">Chart</h6>
           </div>
           <div id="chart-container" class="chart-area-big">

           </div>
       </div>
<button type="button" id="getDataBtn" class="btn btn-success" onclick="GetData();">Update Chart</button>

而我的控制器就像

public IActionResult ChartNew()
        {
            ChartRepository repository = new ChartRepository();
            GeneralObjects.ServiceResponse response = repository.GetChartData();
            List<Devices> tmpList = repository.GetCustomerDevices();
            ViewData["CustomerDevices"] = new Microsoft.AspNetCore.Mvc.Rendering.SelectList(tmpList, "Id", "SerialNumber");

            string query = "SELECT mqttpacket_1606008363.id, datatypes.data_name ,mqttpacket_1606008363.data_value,packetinformation.inserted_time  FROM mqttpacket_1606008363 JOIN packetinformation ON mqttpacket_1606008363.packet_id = packetinformation.id JOIN datatypes ON mqttpacket_1606008363.data_type_id = datatypes.id WHERE packetinformation.inserted_time BETWEEN '2021-03-04 10:44:55.544398' AND '2021-03-05 10:49:55.544398' AND data_type_id = 5 ORDER BY inserted_time asc;";
            response = repository.GetChartData(query);

            ViewBag.ChartText = $"Reading Values of {ViewBag.DataPointName1} and {ViewBag.DataPointName2}";
            ViewBag.AllData = response.This_Object;


            System.Data.DataTable dt = repository.GetDataTypes();
            return View(dt);
        }
        [HttpPost]
        public GeneralObjects.RES UpdateChart()
        {
            
            ChartRepository repository = new ChartRepository();

            string deviceSerialNo = HttpContext.Session.GetString("currentSerialNumber") != null ? HttpContext.Session.GetString("currentSerialNumber").ToString() : "1606008363";
            string selectedDataTypes = HttpContext.Request.Form["chkBox"].ToString();

            string query = repository.PrepSelectQuery(selectedDataTypes, deviceSerialNo, "2021-03-05 10:44:55.544398", "2021-03-11 12:44:55.544398");

            GeneralObjects.ServiceResponse response = repository.GetChartData(query);

            if (response.Return_Code != 0)
                return GeneralObjects.RES.R_NOK;

            TempData["SuccessMSG"] = "Successfull!";
            ViewBag.AllData = response.This_Object;

            return GeneralObjects.RES.R_OKK;
        }

例如当我从屏幕上选择参数时response.ThisObject就像

{type: "line",
markerType:"none",
xValueType:"dateTime",
xValueFormatString:"DDDD MMM YYYY HH:mm:ss",
name:'Discharge',
showInLegend: true,
dataPoints:[{"x":1614937497000.0,"y":315.0},{"x":1614937502000.0,"y":315.0},{"x":1614937507000.0,"y":317.0},{"x":1614937517000.0,"y":320.0},{"x":1614937523000.0,"y":320.0},{"x":1614937528000.0,"y":322.0},{"x":1614937533000.0,"y":322.0},{"x":1614937537000.0,"y":323.0},{"x":1614937543000.0,"y":325.0},{"x":1614937547000.0,"y":325.0},{"x":1614937552000.0,"y":327.0},{"x":1614937563000.0,"y":328.0},{"x":1614937573000.0,"y":330.0},{"x":1614937583000.0,"y":331.0},{"x":1614937588000.0,"y":331.0},{"x":1614937593000.0,"y":332.0},{"x":1614937598000.0,"y":332.0},{"x":1614937603000.0,"y":333.0},{"x":1614937608000.0,"y":334.0}]}
{type: "line",
markerType:"none",
xValueType:"dateTime",
xValueFormatString:"DDDD MMM YYYY HH:mm:ss",
name:'subcooling',
showInLegend: true,
dataPoints:[{"x":1614937507000.0,"y":22.0},{"x":1614937513000.0,"y":22.0},{"x":1614937517000.0,"y":24.0},{"x":1614937528000.0,"y":23.0},{"x":1614937537000.0,"y":24.0},{"x":1614937558000.0,"y":26.0},{"x":1614937568000.0,"y":25.0},{"x":1614937573000.0,"y":23.0},{"x":1614937578000.0,"y":23.0},{"x":1614937603000.0,"y":22.0},{"x":1614937613000.0,"y":21.0}]}

我在return GeneralObjects.RES.R_OKK; 之前得到了这个值但是,它没有得到更新......

提前感谢您的任何建议。

【问题讨论】:

    标签: javascript jquery charts asp.net-core-mvc canvasjs


    【解决方案1】:

    使用ajax更新时不要将数据存储在ViewBag中,因为ViewBag中的数据在视图中不会改变。

    我建议你可以直接在更新动作中返回数据。

    一个简单的例子从Official Site改过来

    @{
        ViewData["Title"] = "Home Page";
    }
    
    <div id="chartContainer" style="height: 370px; width: 100%;"></div>
    
    <button type="button" id="getDataBtn" class="btn btn-success" onclick="Update();">Update Chart</button>
    @section scripts{
    
        <script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
        <script src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
        <script>
    
            var dataPoints = [];
            var chart
            function addData(data) {
    
                for (var i = 0; i < data.length; i++) {
                    dataPoints.push({
                        x: new Date(data[i].x),
                        y: data[i].y
                    });
                }
    
                chart = new CanvasJS.Chart("chartContainer", {
                    animationEnabled: true,
                    theme: "light2",
                    title: {
                        text: "Lenovo Group Stock Price-2017"
                    },
                    axisY: {
                        title: "In HK$",
                        titleFontSize: 24
                    },
                    data: [{
                        type: "line",
                        yValueFormatString: "HK$#,###",
                        dataPoints: dataPoints
                    }]
                });
                chart.render();
            }
    
            window.onload = function () {
                $.ajax({
                    method: 'get',
                    url: '/home/json',
                    success: function (data) {
                        addData(data)
                    }
                })
            }
    
            function Update() {
                dataPoints = [];
                $.ajax({
                    method: 'get',
                    url: '/home/json2',
                    success: function (data) {
                        addData(data)
                    }
                })
            
            }
        </script>
    }
    

    控制器:

    public IActionResult Index()
    {
        return View();
    }
    
    public ContentResult JSON()
    {
        List<DataPoint> dataPoints = new List<DataPoint>();
        dataPoints.Add(new DataPoint(1481999400000, 4.67));
        dataPoints.Add(new DataPoint(1482604200000, 4.7));
        dataPoints.Add(new DataPoint(1483209000000, 4.96));
        dataPoints.Add(new DataPoint(1483813800000, 5.12));
        dataPoints.Add(new DataPoint(1484418600000, 5.08));
        dataPoints.Add(new DataPoint(1485023400000, 5.11));
        dataPoints.Add(new DataPoint(1485628200000, 5));
        dataPoints.Add(new DataPoint(1486233000000, 5.2));
        dataPoints.Add(new DataPoint(1486837800000, 4.7));
        dataPoints.Add(new DataPoint(1487442600000, 4.74));
    
        JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
        return Content(JsonConvert.SerializeObject(dataPoints, _jsonSetting), "application/json");
    }
    
    public ContentResult JSON2()
    {
        List<DataPoint> dataPoints = new List<DataPoint>();
        dataPoints.Add(new DataPoint(1481999400000, 4.67));
        dataPoints.Add(new DataPoint(1482604200000, 4.7));
        dataPoints.Add(new DataPoint(1483209000000, 4.96));
        dataPoints.Add(new DataPoint(1483813800000, 5.12));
        dataPoints.Add(new DataPoint(1484418600000, 5.08));
        dataPoints.Add(new DataPoint(1485023400000, 5.11));
        dataPoints.Add(new DataPoint(1485628200000, 5));
        dataPoints.Add(new DataPoint(1486233000000, 5.2));
        dataPoints.Add(new DataPoint(1486837800000, 4.7));
        dataPoints.Add(new DataPoint(1487442600000, 4.74));
        dataPoints.Add(new DataPoint(1488047400000, 4.67));
        dataPoints.Add(new DataPoint(1488652200000, 4.66));
        dataPoints.Add(new DataPoint(1489257000000, 4.86));
        dataPoints.Add(new DataPoint(1489861800000, 4.91));
        dataPoints.Add(new DataPoint(1490466600000, 5.12));
        dataPoints.Add(new DataPoint(1491071400000, 5.4));
        dataPoints.Add(new DataPoint(1491676200000, 5.08));
        dataPoints.Add(new DataPoint(1492281000000, 5.05));
        dataPoints.Add(new DataPoint(1492885800000, 4.98));
        dataPoints.Add(new DataPoint(1493490600000, 4.89));
        dataPoints.Add(new DataPoint(1494095400000, 4.9));
        dataPoints.Add(new DataPoint(1494700200000, 4.95));
        dataPoints.Add(new DataPoint(1495305000000, 4.88));
        dataPoints.Add(new DataPoint(1495909800000, 5.07));
        JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
        return Content(JsonConvert.SerializeObject(dataPoints, _jsonSetting), "application/json");
    }
    

    【讨论】:

    • 感谢您的建议和努力。但这里的事情是我的数据类型可以在每次更新按钮点击时以不同的方式选择。这意味着例如用户可以在第一次加载时选择复选框“x,y,z”作为数据点,然后可以在第二次选择中选择“x,t,w”,还可以更改图表的持续时间。但我认为我可以整合从函数返回的完整数据,而不是使用 Viewbag。谢谢
    • 就是这样!这里的主要问题是 ViewBag。
    • 是的。我刚刚通过在控制台上转储 ViewBag 值进行了验证,发现该值没有改变。非常感谢。
    【解决方案2】:

    问题是您试图在客户端从后端接收数据之前渲染图表。只是后端的数据还没有,每次点击按钮,这就是为什么它没有任何东西渲染。

    从后端收到数据后尝试调用chart.render()

    【讨论】:

    • 是的,这是有道理的。但是我尝试在AJAX中调用chart.render()success:,结果是一样的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多