简体   繁体   中英

Unable to render two datasets from the controller in View

I am trying to draw a two-line chart with two datasets that share the same labels using chart.js on my ASP.NET MVC app.

I am only getting the data from "Value" plotted on the chart and not "Age" and I cannot find the reason why.

Relevant Controller code:

public ActionResult GetLineChartData() 
{
    List <LineChartData> dataForLineChart = new List <LineChartData> ();
    dataForLineChart.Add(new LineChartData {
        Date = DateTime.NOW, Value = 100, Age = 20
    });
    return Json(dataForLineChart, JsonRequestBehavior.AllowGet);
}

Relevant View code:

$.ajax({
  type: "Post",
  url: '@Url.Action("GetLineChartData", "Posts")',
  contentType: false,
  processData: false,
  data: dataFromForm,
  dataType: "json",
  traditional: true,
  success: function (data) {
    console.log(data);

    var labels = data.map(function (e) {
      return e.Date;
    });

    var data = data.map(function (e) {
      return e.Value;
    });

    var data2 = data.map(function (e) {
      return e.Age;
    });

    var ctx = scatterChart.getContext('2d');

    var config = {
      type: 'line',
      data: {
        labels: labels,
        datasets: [{
            label: "Test"
            data: data,
            backgroundColor: 'rgba(0, 119, 204, 0.3)'
          },
          {
            label: "Test",
            data: data2,
            backgroundColor: 'rgba(242, 204, 143, 1)'
          }
        ]
      }
    };
  }
});

(Some code I do not consider important is hidden)

Issue & Concern

Because the below line overwrites the original data value.

var data = data.map(function (e) {
  return e.Value;
});

After the above line, now the data array was overwritten as an array of integers instead of an array of objects. Based on your sample response from API, the current value of data will be: [100] .

var data2 = data.map(function (e) {
  return e.Age;
});

From the above line, it can't find the Age property in the element. Hence the result of data2 will be: [undefined] .

This is why the data2 is not rendered in the chart.


Solution

Create another variable for the data transformation to avoid overwriting the existing data value.

var dataset = data.map(function (e) {
  return e.Value;
});

var dataset2 = data.map(function (e) {
  return e.Age;
});

var config = {
  type: 'line',
  data: {
    labels: labels,
    datasets: [
      {
        label: 'Test',
        data: dataset,
        backgroundColor: 'rgba(0, 119, 204, 0.3)',
      },
      {
        label: 'Test',
        data: dataset2,
        backgroundColor: 'rgba(242, 204, 143, 1)',
      },
    ],

  },
};

Demo @ StackBlitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM