Chartjs-ChartJS get data from Controller

1👍

I have same issue, but I have already fix it.
Please see full detailed example here:

Model:

//for Pass data to Chart
    public class Dataset
    {
        public Dataset()
        {
            data = new List<int>();
        }
        public string label { get; set; }
        public string fillColor { get; set; }
        public string strokeColor { get; set; }
        public string pointColor { get; set; }
        public List<int> data { get; set; }
    }

    public class RootObject
    {
        public RootObject()
        {
            labels = new List<string>();
            datasets = new List<Dataset>();
        }
        public List<string> labels { get; set; }
        public List<Dataset> datasets { get; set; }
    }

Controller:

public ActionResult Chart()
        {
           //Get data from DB, items is list of objects:
           //1. DisplayText - (string) - chart columns names (equals "labels")
           //2. Value - (int) - chart values (equals "data")   
           var items = _Layer.GetData().ToList(); 

           //check if data exists
           if (items.Any())
            {
                string color = "#3c8dbc";
                Dataset ds = new Dataset
                {
                    label = string.Empty,
                    fillColor = color,
                    pointColor = color,
                    strokeColor = color
                };

                var data = items.Select(x => x.Value).ToList();
                ds.data.AddRange(data);
                model.datasets.Add(ds);

                var labels = items.Select(x => x.DisplayText).ToList();
                model.labels = labels;
            }

            var json = JsonConvert.SerializeObject(model, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });

            return PartialView("_Chart", json);
        }

View:

@model String
<!-- ChartJS 1.0.1 -->
<script src="~/Assets/plugins/chartjs/Chart.min.js" type="text/javascript"></script>

<!-- BAR CHART -->
  <div class="chart">
     <canvas id="barChart" height="230"></canvas>
  </div>

<script>
    //-------------
    //- BAR CHART -
    //-------------
    var barChartCanvas = $("#barChart").get(0).getContext("2d");
    var barChart = new Chart(barChartCanvas);
    //pass chart to Data from Controller
    var barChartData = JSON.parse(@Html.Raw(Json.Encode(Model)));

    var barChartOptions = {
        //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
        scaleBeginAtZero: true,
        //Boolean - Whether grid lines are shown across the chart
        scaleShowGridLines: true,
        //String - Colour of the grid lines
        scaleGridLineColor: "rgba(0,0,0,.05)",
        //Number - Width of the grid lines
        scaleGridLineWidth: 1,
        //Boolean - Whether to show horizontal lines (except X axis)
        scaleShowHorizontalLines: true,
        //Boolean - Whether to show vertical lines (except Y axis)
        scaleShowVerticalLines: true,
        //Boolean - If there is a stroke on each bar
        barShowStroke: true,
        //Number - Pixel width of the bar stroke
        barStrokeWidth: 2,
        //Number - Spacing between each of the X value sets
        barValueSpacing: 5,
        //Number - Spacing between data sets within X values
        barDatasetSpacing: 1,
        //String - A legend template
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
        //Boolean - whether to make the chart responsive
        responsive: true,
        maintainAspectRatio: false
    };

    barChartOptions.datasetFill = false;
    barChart.Bar(barChartData, barChartOptions);
</script>

Leave a comment