Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

c# - 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.

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...