3

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>
mustang00
  • 313
  • 2
  • 9
  • 23
  • 1
    Hey @StephenMuecke, would you mind taking a look at this? Maybe you'll have a better understanding of how to tackle this. – mustang00 Sep 12 '15 at 11:22

2 Answers2

4

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>
Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56
0

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.

RajeshVerma
  • 1,087
  • 9
  • 13
  • When you refer to `db.tblCharts` - where is that coming from? – mustang00 Sep 13 '15 at 08:50
  • Oh, because its throwing up an error saying that it doesn't exist. – mustang00 Sep 13 '15 at 09:03
  • If you need any help from my end please let me know. – RajeshVerma Sep 13 '15 at 09:04
  • I have used following Db Script Create table tblChart ( Id Int primary key Identity(1,1), Years varchar(20) , Sale varchar(20), Purchase varchar(20) ) Insert into tblChart values(2009,2000,2100) Insert into tblChart values(2010,1000,1400) Insert into tblChart values(2011,3000,2900) Insert into tblChart values(2012,1500,2400) Insert into tblChart values(2013,2300,2300) Insert into tblChart values(2014,500,1500) – RajeshVerma Sep 13 '15 at 09:06
  • Oh so that's the table with your data? Now in my case, the table is Product, with number values for sales and purchases? So how would it affect the code in that sense? – mustang00 Sep 13 '15 at 09:08
  • How you fetching data from database means using entity framework or by using ado.net query/procedure? – RajeshVerma Sep 13 '15 at 09:13
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/89509/discussion-between-mustang00-and-rajeshverma). – mustang00 Sep 13 '15 at 09:15