简体   繁体   English

如何使用首先通过代码创建的数据库中的数据填充谷歌图表 - ASP.Net MVC

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

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 idea how because I'm still pretty new to this.但是,我真的不知道该怎么做,因为我对此还是很陌生。 The Google Chart works perfectly with the hard coded values, but how to approach it using actual data from my database is where my understanding ends.谷歌图表与硬编码值完美配合,但如何使用我数据库中的实际数据来处理它是我理解的终点。 There are plenty of tutorials out (on Code First) on how to do this using hard coded data but none on using data from the database .有很多关于如何使用硬编码数据执行此操作的教程(关于 Code First),但没有关于使用数据库数据的教程。

Can someone please provide me with a detailed approach on how to do this so that I can understand it better?有人可以向我提供有关如何执行此操作的详细方法,以便我更好地理解它吗? I'll greatly appreciate it and thanks in advance!我将不胜感激,并提前致谢!

If there is any additional information required please let me know and I will try to add it in to the question.如果需要任何其他信息,请告诉我,我会尝试将其添加到问题中。

Model:模型:

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

Controller:控制器:

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

View:看法:

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

While you could easily generate strings from your entities I am going to use Ajax and JSON as an alternative.虽然您可以轻松地从实体生成字符串,但我将使用 Ajax 和 JSON 作为替代方案。

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:在你的DbContext是这样的:

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.现在在 action 方法中,您可以删除GetChartData()因为我们将从 Ajax 调用中获取图表数据。

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:添加一个新的 action 方法来获取数据表单 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);
}

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>

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.我希望这能解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从文本文件 asp.net Mvc 代码优先填充数据库 - Populate Database From a Text File asp.net Mvc Code First 具有MVC数据库的ASP.NET MVC Google图表 - ASP.NET MVC Google Charts with MVC database 如何使用ASP.net MVC从数据库中获取数据? - How to fetch data from database using ASP.net MVC? 通过AJAX从ASP.NET数据库中选择数据(ASP.NET MVC) - Select data from database via AJAX (ASP.NET MVC) 如何首先使用代码在已创建的数据库中创建ASP.net身份表? - How to create ASP.net identity tables in an already created database using code first? 如何在asp.net mvc EF代码中使用linq查询关系1:N和N:N(在3个实体之间)从数据库中获取数据? - how to fetch data from database using linq query for relationship 1:N and N:N (between 3 entity) in asp.net mvc EF code first? 如何使用“代码优先实体框架”在ASP.NET MVC 4中创建数据库并将其连接到数据库? - How to create a database and connect to it in ASP.NET MVC 4 by using Code First Entity Framework? 将ASP.NET MVC与Javascript Google Charts结合使用 - Using ASP.NET MVC with Javascript Google Charts 谷歌图表和asp.net MVC - Google Charts and asp.net MVC 如何在ASP.NET MVC应用程序中首先使用EF代码检查SQL表中是否存在数据? - How to check if data exist in SQL table using EF code first in ASP.NET MVC application?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM