如何使用代码优先创建的数据库中的数据填充 google 图表 - ASP.Net MVC

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

我想用我使用代码优先方法创建的数据库中的数据替换下面代码中的硬编码数据。

但是,我真的不知道怎么做,因为我对此还是很陌生。 Google 图表与硬编码值完美配合,但如何使用我数据库中的实际数据来处理它是我理解的终点。关于如何使用硬编码数据执行此操作的教程很多(关于 Code First),但是 none 使用数据库中的数据[=34] =].

有人可以向我提供有关如何执行此操作的详细方法,以便我更好地理解它吗?非常感谢并提前致谢!

如果需要任何其他信息,请告诉我,我会尝试将其添加到问题中。

型号:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HealthHabitat.Models
{
    public class ProductModel
    {
        public string YearTitle { get; set; }
        public string SaleTitle { get; set; }
        public string PurchaseTitle { get; set; }
        public Product ProductData { get; set; }
    }
    public class Product
    {
        public string Year { get; set; }
        public string Purchase { get; set; }
        public string Sale { get; set; }
    }
}

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HealthHabitat.Models;

namespace HealthHabitat.Controllers
{
    public class ChartController : Controller
    {
        //
        // GET: /Home/

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

        }
        /// <summary>
        /// Code to get the data which we will pass to chart
        /// </summary>
        /// <returns></returns>
        public Product GetChartData()
        {
            Product objproduct = new Product();
            /*Get the data from databse and prepare the chart record data in string form.*/
            objproduct.Year = "2009,2010,2011,2012,2013,2014";
            objproduct.Sale = "2000,1000,3000,1500,2300,500";
            objproduct.Purchase = "2100,1400,2900,2400,2300,1500";
            return objproduct;
        }
    }
}

查看:

 @model HealthHabitat.Models.ProductModel

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

    google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);

    function drawChart() {
        // Create and populate the data table.
        var years = [@Model.ProductData.Year];
        var sales = [@Model.ProductData.Sale];
        var Purchase = [@Model.ProductData.Purchase];

        var data = new google.visualization.DataTable();
        data.addColumn('string', '@Model.YearTitle');
        data.addColumn('number', '@Model.SaleTitle');
        data.addColumn('number', '@Model.PurchaseTitle');
        for (i = 0; i < years.length; i++) {
            data.addRow([years[i].toString(), sales[i], Purchase[i]]);
        }
        var options = {
            title: 'Sale and Purchase Compare',
            hAxis: { title: '@Model.YearTitle', titleTextStyle: { color: 'red'} }
        };

        var chart = newgoogle.visualization.ColumnChart(document.getElementById('chartdiv'));
        chart.draw(data, options);
    }
</script>
<div id="chartdiv" style="width: 500px; height: 300px;">
</div>

虽然您可以轻松地从您的实体生成字符串,但我将使用 Ajax 和 JSON 作为替代方法。

假设你有这样的实体模型:

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

在你的 DbContext 中是这样的:

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

现在在操作方法中,您可以删除 GetChartData(),因为我们将从 Ajax 调用中获取图表数据。

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

添加一个新的操作方法来获取数据表单 Ajax 调用:

// 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);
}

现在你的视图可能是这样的:

<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>

您可以尝试使用以下方式

 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;
    }

希望能解决您的问题。