How to pass data to View generate a chart with Chart.js

0

I need to generate a line chart with chart.js. How can I pass data to my View? I'm trying as below, but the graph does not appear.

Controller

public IActionResult Index() 
{ 
    var qryGlobal = _diagnosticRepository.GetAll() 
    .Where(u => u.UserName == User.Identity.Name)
    .GroupBy(x => x.Month).ToList(); 
    
    List<string> legend = new List<string>(); 
    List<double> valuesY = new List<double>(); 
    
    foreach(var i in qryGlobal) 
    { 
        var valueRevenue = i.Where(x => x.DfpChartOfAccounts.Category.Equals("Faturamento"))
        .Select(x => x.Value).ToList(); 
        
        double val = Convert.ToDouble(valueRevenue[0]); 
        var valueSum = i.Sum(x => x.Value); 
        double result = Convert.ToDouble(valueSum) - val; 
        
        legend.Add(i.Key.ToString());        
        valuesY.Add(result); 
     } 

     ViewBag.XLabels = legend.ToList(); 
     ViewBag.YValues = valuesY.ToList(); 
        
     return View(); 
}

In my View I'm doing this:

@{ 
    var XLabels = (List<string>)ViewBag.XLabels;
    var YValues = (List<double>)ViewBag.YValues;
}
 
<div><canvas class="graph-main"></canvas></div>
.
.
.
.
.

<script type="text/javascript">

    var ctx = document.getElementsByClassName("graph-main");
    var chartGraphMain = new Chart(ctx, {
        type: 'line',
        data: {
            labels: @XLabels.ToArray(),
            datasets: [{
                backgroundColor: 'rgba(70,130,180, 0.5)',
                pointBorderWidth: 1,
                pointBackgroundColor: "rgba(70,130,180,1)",
                pointRadius: 3,
                pointBorderColor: '#ffffff',
                borderWidth: 1,
                data: @YValues.ToArray(),
                
            }]
        },
        options: ...... //configurações
    });
</script>
    
asked by anonymous 27.10.2018 / 19:59

0 answers