Thursday, March 12, 2009

Create a MVC Helper to Display a Microsoft Chart Control




1. Add a reference to C:\Program Files\Microsoft Chart Controls\Assemblies\System.Web.DataVisualization.dll and C:\Program Files\Microsoft Chart Controls\Assemblies\System.Web.DataVisualization.Design.dll

---Helper Class --

2. using System.Web.UI.DataVisualization.Charting;

3. Add static method.


public static void Chart(this HtmlHelper helper, string polltitle, List<int> values, List<string> labels, int width, int height, SeriesChartType ChartType, System.Web.UI.Page page)
{
System.Web.UI.DataVisualization.Charting.Chart Chart1 = new System.Web.UI.DataVisualization.Charting.Chart();
Chart1 = new System.Web.UI.DataVisualization.Charting.Chart();
Chart1.Width = width;
Chart1.Height = height;
Chart1.RenderType = RenderType.ImageTag;
// Populate series data
Chart1.Series.Add("Default");
Chart1.ChartAreas.Add("ChartArea1");
Chart1.Series["Default"].Points.DataBindXY(labels, values);

// Set Doughnut chart type
Chart1.Series["Default"].ChartType = ChartType;

// Set labels style
Chart1.Series["Default"]["PieLabelStyle"] = "outside";

Chart1.Titles.Add(polltitle);
// Enable 3D
Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;

// Disable the Legend
//Chart1.Legends[0].Enabled = false;


// Render chart control
Chart1.Page = page;
HtmlTextWriter writer = new HtmlTextWriter(page.Response.Output);
Chart1.RenderControl(writer);


}


4. In your view page.



<%Html.Chart(ViewData["charttitle"].ToString(), (List<int>)ViewData["chartvalues"], (List<string>)ViewData["chartlabels"], 400, 400, SeriesChartType.Pie, this); %>


Obvisouly you could go nuts in your helper method and have all kind of different options like enable 3d, show title, color etc etc.

Enjoy.

2 comments:

Mungyun said...
This comment has been removed by the author.
Unknown said...

Thanks a lot!