[英]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.