您可以通过两种方式使用图表控件:
从控制器生成图像
通过生成图表并将其作为操作中的图像返回(我认为 Chatuman 指的是):
Chart chart = new Chart();
chart.BackColor = Color.Transparent;
chart.Width = Unit.Pixel(250);
chart.Height = Unit.Pixel(100);
Series series1 = new Series("Series1");
series1.ChartArea = "ca1";
series1.ChartType = SeriesChartType.Pie;
series1.Font = new Font("Verdana", 8.25f, FontStyle.Regular);
series1.Points.Add(new DataPoint {
AxisLabel = "Value1", YValues = new double[] { value1 } });
series1.Points.Add(new DataPoint {
AxisLabel = "Value2", YValues = new double[] { value2 } });
chart.Series.Add(series1);
ChartArea ca1 = new ChartArea("ca1");
ca1.BackColor = Color.Transparent;
chart.ChartAreas.Add(ca1);
using (var ms = new MemoryStream())
{
chart.SaveImage(ms, ChartImageFormat.Png);
ms.Seek(0, SeekOrigin.Begin);
return File(ms.ToArray(), "image/png", "mychart.png");
}
WebForms 样式
这样您只需将图表包含在您的 .aspx 视图中(就像使用传统的 Web 表单一样)。为此,您必须在 web.config 中连接相关位
<controls>
...
<add tagPrefix="asp"
namespace="System.Web.UI.DataVisualization.Charting"
assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
<httpHandlers>
...
<add path="ChartImg.axd"
verb="GET,HEAD"
validate="false"
type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</httpHandlers>
<handlers>
...
<add name="ChartImageHandler"
preCondition="integratedMode"
verb="GET,HEAD"
path="ChartImg.axd"
type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>
构建图表时,您无法在 DataPoint 元素中运行代码,因此要连接数据,您需要 View 类中的方法。这对我来说没问题。以这种方式工作会使控件将 URL 呈现到由图表控件 http 处理程序生成的图像。在您的部署中,您需要为其提供一个可写文件夹来缓存图像。
* VS 2010 / .NET 4 支持 *
要在 .NET 4 中使用此功能,您需要使用适当的公钥令牌将图表引用更改为版本 4.0.0.0。
此外,图表控件现在似乎生成了指向当前请求路径而不是请求路由的 url。对我来说,这意味着所有图表请求都会导致 404 错误,因为 /{Controller}/ChartImg.axd 和等效项被路由阻止。为了解决这个问题,我添加了额外的 IgnoreRoute 调用来涵盖我的用法 - 更通用的解决方案会更好:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("ChartImg.axd/{*pathInfo}");
routes.IgnoreRoute("{controller}/ChartImg.axd/{*pathInfo}");
routes.IgnoreRoute("{controller}/{action}/ChartImg.axd/{*pathInfo}");
...