How to populate google charts using data from database created via code first - ASP.Net MVC

后端 未结 2 856
庸人自扰
庸人自扰 2020-12-21 08:33

I want to replace the hard coded data in the code below with data from my database that I\'ve created using the Code First approach.

However, I literally have no ide

相关标签:
2条回答
  • 2020-12-21 09:05

    You can try using following way

     public Product GetChartData()
        {
            Product objproduct = new Product();
    
            List<string> yr = null;
            List<string> sal = null;
            List<string> pur = null;
    
            yr = db.tblCharts.Select(y => y.Years).ToList();
            sal = db.tblCharts.Select(y => y.Sale).ToList();
            pur = db.tblCharts.Select(y => y.Purchase).ToList();
            objproduct.Year = string.Join(",", yr);
            objproduct.Sale = string.Join(",", sal);
            objproduct.Purchase = string.Join(",", pur);
    
            return objproduct;
        }
    

    I hope that will resolve your problem.

    0 讨论(0)
  • 2020-12-21 09:14

    While you could easily generate strings from your entities I am going to use Ajax and JSON as an alternative.

    Imaging you have entity model like this:

    public class Product
    {
        public int ID {get; set; }
        public int Year { get; set; }
        public int Purchase { get; set; }
        public int Sale { get; set; }
    }
    

    And in your DbContext is something like this:

    public class Mycontext:DbContext
    {
        public IDbSet<Product> Products { get; set; }
        // other sets 
    }
    

    Now in action method you could remove GetChartData() since we are going to get chart data from Ajax call.

    public ActionResult Index()
    {
        ProductModel objProductModel = new ProductModel();
        objProductModel.YearTitle = "Year";
        objProductModel.SaleTitle = "Sale";
        objProductModel.PurchaseTitle = "Purchase";
        return View(objProductModel);
    }
    

    Add a new action method to get data form Ajax call:

    // in real world you may add some parameters to filter your data  
    public ActionResult GetChart()
    {
        return Json(_myDB.Products
            // you may add some query to your entitles 
            //.Where()
            .Select(p=>new{p.Year.ToString(),p.Purchase,p.Sale}),
                JsonRequestBehavior.AllowGet);
    }
    

    Now your view could be like this:

    <script type="text/javascript">
    
      // Load the Visualization API and the piechart package.
      google.load('visualization', '1.0', {'packages':['corechart']});
    
      // Set a callback to run when the Google Visualization API is loaded.
      google.setOnLoadCallback(drawChart);
    
      function drawChart() {
          var data = new google.visualization.DataTable();
          data.addColumn('string', '@Model.YearTitle');
          data.addColumn('number', '@Model.SaleTitle');
          data.addColumn('number', '@Model.PurchaseTitle');
    
          // don't forget to add JQuery in your view. 
          $.getJSON("@Url.Action("GetChart")", null, function (chartData) {
              $.each(chartData, function (i, item) {
                  data.addRow([item.Year, item.Sale, item.Purchase]);
              });
    
              var options = {
                  title: 'Sale and Purchase Compare',
                  hAxis: { title: '@Model.YearTitle', titleTextStyle: { color: 'red' } }
              };
    
              var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
              chart.draw(data, options);
          });
      }
    </script>
    
    0 讨论(0)
提交回复
热议问题