我已经被困在这几天了。
我在SQL Server中创建了一个名为HoursPerSite的表。我现在使用该表作为我的mvc项目中的模型。
我正在尝试实施谷歌图表来显示此表中的数据,但因此图表不会出现在我的网络应用程序上。
这是代码:
控制器:
using HolidayTracker.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
namespace HolidayTracker.Controllers
{
public class MetricsController : Controller
{
#region Index method
/// <summary>
/// GET: Home/Index method.
/// </summary>
/// <returns>Returns - index view page</returns>
public ActionResult Index()
{
GetData();
LoadData();
// Info.
return this.View();
}
#endregion
#region Get data method.
/// <summary>
/// GET: /Home/GetData
/// </summary>
/// <returns>Return data</returns>
public ActionResult GetData()
{
// Initialization.
JsonResult result = new JsonResult();
try
{
// Loading.
List<HoursPerSite> data = this.LoadData();
// Setting.
var graphData = data.GroupBy(p => new
{
p.SiteName,
p.SiteHours
})
.Select(g => new
{
g.Key.SiteName,
g.Key.SiteHours
}).OrderByDescending(q => q.SiteName).ToList();
// Top 10
graphData = graphData.Take(10).Select(p => p).ToList();
// Loading drop down lists.
result = this.Json(graphData, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
// Info
Console.Write(ex);
}
// Return info.
return result;
}
#endregion
#region Helpers
#region Load Data
/// <summary>
/// Load data method.
/// </summary>
/// <returns>Returns - Data</returns>
private List<HoursPerSite> LoadData()
{
// Initialization.
List<HoursPerSite> lst = new List<HoursPerSite>();
try
{
//// Initialization.
//string line = string.Empty;
//string srcFilePath = "Content/files/SalesOrderDetail.txt";
//var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
//var fullPath = Path.Combine(rootPath, srcFilePath);
//string filePath = new Uri(fullPath).LocalPath;
//StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));
//// Read file.
//while ((line = sr.ReadLine()) != null)
//{
// // Initialization.
// Employee infoObj = new Employee();
// string[] info = line.Split(',');
// // Setting.
// infoObj.FullName = info[3].ToString();
// infoObj.HoursTaken = Convert.ToDecimal(info[0].ToString());
// infoObj.SickLeaveTaken = Convert.ToDecimal(info[0].ToString());
// // Adding.
// lst.Add(infoObj);
//}
//// Closing.
//sr.Dispose();
//sr.Close();
}
catch (Exception ex)
{
// info.
Console.Write(ex);
}
// info.
return lst;
}
#endregion
#endregion
}
脚本:
// 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.
$(document).ready(function () {
$.ajax(
{
type: 'POST',
dataType: 'JSON',
url: '/Metrics/GetData',
success:
function (response) {
// Set chart options
var options =
{
width: 1100,
height: 900,
sliceVisibilityThreshold: 0,
legend: { position: "top", alignment: "end" },
chartArea: { left: 370, top: 50, height: "90%" },
hAxis:
{
slantedText: true,
slantedTextAngle: 18
},
bar: { groupWidth: "50%" },
};
// Draw.
drawGraph(response, options, 'graphId');
}
});
});
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawGraph(dataValues, options, elementId) {
// Initialization.
var data = new google.visualization.DataTable();
// Setting. C:\Projects\HolidayTrackerMainProject\HolidayTracker - Working - 04-03 - Copy\HolidayTracker\Scripts/
data.addColumn('string', 'Site Name');
data.addColumn('number', 'Hours');
// Processing.
for (var i = 0; i < dataValues.length; i++) {
// Setting.
data.addRow([dataValues[i].SiteName, dataValues[i].SiteHours]);
}
// Setting label.
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2,
{
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
}
]);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById(elementId));
// Draw chart.
chart.draw(view, options);
}
我在哪里错了?如何让我的webapp显示包含db数据的简单条形图或饼图。
谢谢
萨拉斯一年的图表
将此操作添加到您的控制器
public ActionResult ChartShow()
{
DateTime TM = DateTime.Now;
DateTime FromDate1 = new DateTime(TM.Year, 01, 01);
DateTime ToDate1 = new DateTime(FromDate1.Year, FromDate1.Month, DateTime.DaysInMonth(FromDate1.Year, FromDate1.Month));
string S1 = db.TBLInvoices.Where(c => (c.INDate) >= FromDate1 && (c.INDate) <= ToDate1 && c.INActive == true).Sum(c => c.INTotal).GetValueOrDefault().ToString();
DateTime FromDate2 = new DateTime(TM.Year, 02, 01);
DateTime ToDate2 = new DateTime(FromDate2.Year, FromDate2.Month, DateTime.DaysInMonth(FromDate2.Year, FromDate2.Month));
string S2 = db.TBLInvoices.Where(c => (c.INDate) >= FromDate2 && (c.INDate) <= ToDate2 && c.INActive == true).Sum(c => c.INTotal).GetValueOrDefault().ToString();
DateTime FromDate3 = new DateTime(TM.Year, 03, 01);
DateTime ToDate3 = new DateTime(FromDate3.Year, FromDate3.Month, DateTime.DaysInMonth(FromDate3.Year, FromDate3.Month));
string S3 = db.TBLInvoices.Where(c => (c.INDate) >= FromDate3 && (c.INDate) <= ToDate3 && c.INActive == true).Sum(c => c.INTotal).GetValueOrDefault().ToString();
DateTime FromDate4 = new DateTime(TM.Year, 04, 01);
DateTime ToDate4 = new DateTime(FromDate4.Year, FromDate4.Month, DateTime.DaysInMonth(FromDate4.Year, FromDate4.Month));
string S4 = db.TBLInvoices.Where(c => (c.INDate) >= FromDate4 && (c.INDate) <= ToDate4 && c.INActive == true).Sum(c => c.INTotal).GetValueOrDefault().ToString();
DateTime FromDate5 = new DateTime(TM.Year, 05, 01);
DateTime ToDate5 = new DateTime(FromDate5.Year, FromDate5.Month, DateTime.DaysInMonth(FromDate5.Year, FromDate5.Month));
string S5 = db.TBLInvoices.Where(c => (c.INDate) >= FromDate5 && (c.INDate) <= ToDate5 && c.INActive == true).Sum(c => c.INTotal).GetValueOrDefault().ToString();
DateTime FromDate6 = new DateTime(TM.Year, 06, 01);
DateTime ToDate6 = new DateTime(FromDate6.Year, FromDate6.Month, DateTime.DaysInMonth(FromDate6.Year, FromDate6.Month));
string S6 = db.TBLInvoices.Where(c => (c.INDate) >= FromDate6 && (c.INDate) <= ToDate6 && c.INActive == true).Sum(c => c.INTotal).GetValueOrDefault().ToString();
DateTime FromDate7 = new DateTime(TM.Year, 07, 01);
DateTime ToDate7 = new DateTime(FromDate7.Year, FromDate7.Month, DateTime.DaysInMonth(FromDate7.Year, FromDate7.Month));
string S7 = db.TBLInvoices.Where(c => (c.INDate) >= FromDate7 && (c.INDate) <= ToDate7 && c.INActive == true).Sum(c => c.INTotal).GetValueOrDefault().ToString();
DateTime FromDate8 = new DateTime(TM.Year, 08, 01);
DateTime ToDate8 = new DateTime(FromDate8.Year, FromDate8.Month, DateTime.DaysInMonth(FromDate8.Year, FromDate8.Month));
string S8 = db.TBLInvoices.Where(c => (c.INDate) >= FromDate8 && (c.INDate) <= ToDate8 && c.INActive == true).Sum(c => c.INTotal).GetValueOrDefault().ToString();
DateTime FromDate9 = new DateTime(TM.Year, 09, 01);
DateTime ToDate9 = new DateTime(FromDate9.Year, FromDate9.Month, DateTime.DaysInMonth(FromDate9.Year, FromDate9.Month));
string S9 = db.TBLInvoices.Where(c => (c.INDate) >= FromDate9 && (c.INDate) <= ToDate9 && c.INActive == true).Sum(c => c.INTotal).GetValueOrDefault().ToString();
DateTime FromDate10 = new DateTime(TM.Year, 10, 01);
DateTime ToDate10 = new DateTime(FromDate10.Year, FromDate10.Month, DateTime.DaysInMonth(FromDate10.Year, FromDate10.Month));
string S10 = db.TBLInvoices.Where(c => (c.INDate) >= FromDate10 && (c.INDate) <= ToDate10 && c.INActive == true).Sum(c => c.INTotal).GetValueOrDefault().ToString();
DateTime FromDate11 = new DateTime(TM.Year, 11, 01);
DateTime ToDate11 = new DateTime(FromDate11.Year, FromDate11.Month, DateTime.DaysInMonth(FromDate11.Year, FromDate11.Month));
string S11 = db.TBLInvoices.Where(c => (c.INDate) >= FromDate11 && (c.INDate) <= ToDate11 && c.INActive == true).Sum(c => c.INTotal).GetValueOrDefault().ToString();
DateTime FromDate12 = new DateTime(TM.Year, 12, 01);
DateTime ToDate12 = new DateTime(FromDate12.Year, FromDate12.Month, DateTime.DaysInMonth(FromDate12.Year, FromDate12.Month));
string S12 = db.TBLInvoices.Where(c => (c.INDate) >= FromDate12 && (c.INDate) <= ToDate12 && c.INActive == true).Sum(c => c.INTotal).GetValueOrDefault().ToString();
string[] Modes = { S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12 };
ViewData["OurSals"] = Modes;
return View();
}
添加视图
@{
ViewBag.Title = "GoogleSalsChart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row text-center" dir="ltr">
<div class="container-fluid">
<div class="card-header">
<i class="fa fa-table"></i> <b>Chart</b>
</div>
<br />
<div class="row col-md-12">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="top_x_div" style="width: 100%; height: 400px;"></div>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['bar'] });
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Chart', 'Total'],
["1",@(((string[])ViewData["OurSals"])[0])],
["2",@(((string[])ViewData["OurSals"])[1])],
["3",@(((string[])ViewData["OurSals"])[2])],
["4",@(((string[])ViewData["OurSals"])[3])],
["5",@(((string[])ViewData["OurSals"])[4])],
["6",@(((string[])ViewData["OurSals"])[5])],
["7",@(((string[])ViewData["OurSals"])[6])],
["8",@(((string[])ViewData["OurSals"])[7])],
["9",@(((string[])ViewData["OurSals"])[8])],
["10",@(((string[])ViewData["OurSals"])[9])],
["11",@(((string[])ViewData["OurSals"])[10])],
["12",@(((string[])ViewData["OurSals"])[11])]
]);
var options = {
legend: { position: 'none' },
axes: {
x: {
0: { side: 'top' }
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
};
</script>
</div>
</div>
</div>