我正在处理mvc框架的图表助手,我想知道是否有办法将动态数据添加到图表中。 所有教程(例如http://www.asp.net/webmatrix/tutorials/7-displaying-data-in-a-chart)都使用硬编码数据。
如果我想传递数据,例如股票列表并在图表中显示数据,该怎么办。
我将图表包括在内:
<img src="@Url.Action("GenerateChart", new {data = stocks})" alt="stocks" />
动作方法的可能代码:
public FileContentResult GenerateChartImage(IList<StockProgressionModel> data)
{
Chart chart = new Chart(800, 600);
foreach (var stock in data {
int[] xArray = Enumerable.Range(0, stock.Entries.Count).ToArray();
var yArray = stock.Entries.Select(e => e.Value).ToArray();
chart.AddSeries(ap.FieldOfActivityName, chartType: "FastLine",
xValue: xArray,
yValues: yArray);
chart.SetXAxis("Month", 0);
chart.SetYAxis("Value", 0);
}
return File(chart.GetBytes(), "image/png");
}
这意味着url的链接始终相同,我无法将数据作为参数传递。 有更好的方法吗?
答案 0 :(得分:2)
我找到了解决方案:
查看:
@{
string key = Guid.NewGuid().ToString();
@Html.Action("GenerateChart", new { @cacheKey = key, data = stocks })
string url = Url.Action("ShowChart", new { @cacheKey = key });
<img src="@url" alt="Chart" />
}
控制器:
public void GenerateChartImage(IList<StockProgressionModel> data)
{
Chart chart = new Chart(800, 600);
foreach (var stock in data {
int[] xArray = Enumerable.Range(0, stock.Entries.Count).ToArray();
var yArray = stock.Entries.Select(e => e.Value).ToArray();
chart.AddSeries(ap.FieldOfActivityName, chartType: "FastLine",
xValue: xArray,
yValues: yArray);
chart.SetXAxis("Month", 0);
chart.SetYAxis("Value", 0);
}
chart.SaveToCache(cacheKey, 1);
}
public void ShowChart(string cacheKey)
{
Chart chart = Chart.GetFromCache(cacheKey);
chart.Write("jpeg");
}
如果有人有更好的解决方案,我会感兴趣。
答案 1 :(得分:0)
public ActionResult Index()
{
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["DevelopmentConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(cs);
var currentYear = DateTime.Now.Year;
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand($"SELECT top 5 product, itemUnitPrice FROM [Development].[dbo].[Orderslist] WHERE timeStamp LIKE '%{currentYear}%' GROUP BY itemUnitPrice, product order by COUNT(product) desc", con);
con.Open();
System.Data.SqlClient.SqlDataReader rdr = cmd.ExecuteReader();
ViewBag.data = rdr;
return View();
}
.DataBindTable(ViewBag.data, xField: "product")
.Write()