I have a typical setup for displaying charts for MVC3 web page –
Here is the code for all the components.
Controller Code:
public ActionResult ShowChart() {
myViewModel model = _myService.GetViewModel();
return View(model);
}
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; }
}
View: (View.cshtml)
@foreach (System.Web.UI.DataVisualization.Charting.Chart chart in Model.Charts)
{
@chart
}
Chart Builder:
This populates the View Model.
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;
}
But, the code – @chart in the view does not render the chart. what I get in the page is a string ‘System.Web.UI.DataVisualization.Charting.Chart’ in place of the chart image.
Can somebody let me know what is wrong here. How can I output the chart on the view?
Thanks!
You can’t do:
Asp.Net MVC does not know how to render those. What you can do is either request each chart as an image. So follow this tutorial.
You should also move the “Option A” or “Option B” section into an editor template.