我有一个显示MVC3网页图表的典型设置 -
以下是所有组件的代码。
public ActionResult ShowChart() {
myViewModel model = _myService.GetViewModel();
return View(model);
}
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.UI.DataVisualization.Charting;
public class ViewModel {
public List<Chart> Charts { get; set; }
}
@foreach (System.Web.UI.DataVisualization.Charting.Chart chart in Model.Charts)
{
@chart
}
这会填充视图模型。
private List<Chart> BuildCharts(List<Dummy> chartData)
{
var charts = new List<Chart>();
foreach (Dummy chart in chartData)
{
charts.Add(BuildChart(chart));
}
return charts;
}
private Chart BuildChart(Dummy chartData)
{
var data = new ChartData
{
Title = "Chart X",
xValues = chartData.hours,
yValues = chartData.values
};
return ConfigureChart(data);
}
private Chart ConfigureChart(ChartData data)
{
Chart chart = new Chart();
chart.Width = 150;
chart.Height = 300;
chart.Attributes.Add("align", "left");
chart.Titles.Add(data.Title);
chart.ChartAreas.Add(new ChartArea());
chart.Series.Add(new Series());
chart.Legends.Add(new Legend("XXXX_YYY"));
chart.Legends[0].TableStyle = LegendTableStyle.Auto;
chart.Legends[0].Docking = Docking.Bottom;
chart.Series[0].ChartType = SeriesChartType.Line;
chart.Series[0].BackGradientStyle = GradientStyle.DiagonalLeft;
chart.Series[0].BackSecondaryColor = System.Drawing.Color.LightGray;
for (int i = 0; i < data.xValues.Length; i++)
{
string x = data.xValues[i];
decimal y = data.yValues[i];
int ptIdx = chart.Series[0].Points.AddXY(x, y);
DataPoint pt = chart.Series[0].Points[ptIdx];
pt.Url = "/Instance/Index/";
pt.ToolTip = "Tooltip";
pt.LegendText = "#VALX: #VALY";
pt.LegendUrl = "/Contact/Details/";
pt.LegendToolTip = "Click to view dummy information...";
}
return chart;
}
但是,视图中的代码 - @chart不会呈现图表。我在页面中得到的是一个字符串'System.Web.UI.DataVisualization.Charting.Chart'来代替图表图像。
有人可以告诉我这里有什么问题。如何在视图上输出图表?
谢谢!
答案 0 :(得分:4)
你做不到:
@chart
Asp.Net MVC不知道如何渲染它们。您可以做的是要么将每个图表作为图像请求。请按照this tutorial。
您还应将“选项A”或“选项B”部分移至editor template。