我一直在尝试将我的highcharts图表连接到数据库,因此我可以获得实时数据。我尝试连接的表名为dbo.Answers_int。我一直遇到麻烦。我的代码来自此网站https://www.c-sharpcorner.com/UploadFile/1f3f2a/charting-in-mvc/
当我尝试加载页面时,highcharts甚至没有出现。我没有想法。任何帮助将不胜感激。
ReportsController.cs:
public class ReportsController : Controller{
private HHDBEntities db = new HHDBEntities();
public static DataTable GetQuestionSummary()
{
DataTable dt = new DataTable("ChartSummary");
string query = "Select QuestionAns From [dbo].[Answers_int]";
string connString = ConfigurationManager.ConnectionStrings["SampleMembershipDB"].ConnectionString;
SqlConnection con = new SqlConnection(connString);
//con.ConnectionString = "Data Source=.;" + "Initial Catalog=Transport;" + "Persist Security Info=True;";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
//cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(dt);
con.Close();
return dt;
}
public class Summary
{
public double Item { get; set; }
public string Value { get; set; }
}
public JsonResult ChartSummary()
{
List<Summary> lstSummary = new List<Summary>();
foreach (DataRow dr in GetQuestionSummary().Rows)
{
Summary summary = new Summary();
summary.Value = dr[0].ToString().Trim();
summary.Item = Convert.ToDouble(dr[1]);
lstSummary.Add(summary);
}
return Json(lstSummary.ToList(), JsonRequestBehavior.AllowGet);
}
PieChart.cshtml:
$(function () {
$.ajax({
url: 'Reports/PieChart',
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
async: false,
processData: false,
cache: false,
delay: 15,
success: function (data) {
// alert(data);
var series = new Array();
for (var i in data) {
var serie = new Array(data[i].Value, data[i].Item);
series.push(serie);
}
DrawPieChart(series);
},
error: function (xhr) {
alert('error');
}
});
});
function DrawPieChart(series) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: 1, //null,
plotShadow: false
},
title: {
text: ' Vehicle Summary'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Task Status',
data: series
}]
});
}
答案 0 :(得分:0)
您只从数据库中获取一列。您将在示例中看到正在返回2列,其中一列是返回百分比的计算。看起来您需要这个来创建图表。
在本节中
foreach (DataRow dr in GetQuestionSummary().Rows)
{
Summary summary = new Summary();
summary.Value = dr[0].ToString().Trim();
summary.Item = Convert.ToDouble(dr[1]);
lstSummary.Add(summary);
}
您可以看到需要一个项目和一个值。同样,您需要使用2列数据。