HowTo: Use the new ASP.NET Chart Controls with ASP.NET MVC
Microsoft released today a new feature for ASP.NET – free chart controls (which are based on the Dundas Chart Controls). There are many nice looking charts in this download included:
The best thing is: It should work with ASP.NET MVC!
Download links for the ASP.NET Charts (free) :
- Download the free Microsoft Chart Controls
- Download the VS 2008 Tool Support for the Chart Controls
- Download the Microsoft Chart Controls Samples
- Download the Microsoft Chart Controls Documentation
Edit the Web.Config
To enable the controls you have to edit the web.config file.
Add this under the controls tag (path: "<system.web><pages><controls>") :
<add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
And add this httpHandler (under "<httpHandlers>") :
<add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
Via: Combining ASP.NET MVC and ASP.NET Charting Controls
Add a chart control to a view:
Option A: ASP.NET Control + Code behind
If you use this option, you will have to add some code lines in the code behind file of your view. This shouldn´t be a big problem, because the controller is still responsible for the logic.
I took the "GettingStarted" Control from the samples:
Index.aspx:
<asp:chart id="Chart1" runat="server" Height="296px" Width="412px" Palette="BrightPastel" imagetype="Png" BorderDashStyle="Solid" BackSecondaryColor="White" BackGradientStyle="TopBottom" BorderWidth="2" backcolor="#D3DFF0" BorderColor="26, 59, 105"> <Titles> <asp:Title Text="With datasource in code behind" /> </Titles> <legends> <asp:Legend IsTextAutoFit="False" Name="Default" BackColor="Transparent" Font="Trebuchet MS, 8.25pt, style=Bold"></asp:Legend> </legends> <borderskin skinstyle="Emboss"></borderskin> <series> <asp:Series Name="Column" BorderColor="180, 26, 59, 105"> </asp:Series> </series> <chartareas> <asp:ChartArea Name="ChartArea1" BorderColor="64, 64, 64, 64" BorderDashStyle="Solid" BackSecondaryColor="White" BackColor="64, 165, 191, 228" ShadowColor="Transparent" BackGradientStyle="TopBottom"> <area3dstyle Rotation="10" perspective="10" Inclination="15" IsRightAngleAxes="False" wallwidth="0" IsClustered="False"></area3dstyle> <axisy linecolor="64, 64, 64, 64"> <labelstyle font="Trebuchet MS, 8.25pt, style=Bold" /> <majorgrid linecolor="64, 64, 64, 64" /> </axisy> <axisx linecolor="64, 64, 64, 64"> <labelstyle font="Trebuchet MS, 8.25pt, style=Bold" /> <majorgrid linecolor="64, 64, 64, 64" /> </axisx> </asp:ChartArea> </chartareas> </asp:chart>
I don´t know the exactly meaning of each line (read the documentation to lern more about it), but the important point is that we have a "Serie" with name " "Column" – this will represent your data as a bar in your bar chart.
Index.aspx.cs:
public partial class Index : ViewPage
{
protected void Page_Load(object sender, System.EventArgs e)
{
foreach (int value in (List<int>)this.ViewData["Chart"])
{
this.Chart1.Series["Column"].Points.Add(value);
}
}
}
Result:
Option B: Inline ASP.NET Control
You could also create the control without a code behind file, just create the control on the fly via inline code:
<p>
<%
System.Web.UI.DataVisualization.Charting.Chart Chart2 = new System.Web.UI.DataVisualization.Charting.Chart();
Chart2.Width = 412;
Chart2.Height = 296;
Chart2.RenderType = RenderType.ImageTag;
Chart2.Palette = ChartColorPalette.BrightPastel;
Title t = new Title("No Code Behind Page", Docking.Top, new System.Drawing.Font("Trebuchet MS", 14, System.Drawing.FontStyle.Bold), System.Drawing.Color.FromArgb(26, 59, 105));
Chart2.Titles.Add(t);
Chart2.ChartAreas.Add("Series 1");
// create a couple of series
Chart2.Series.Add("Series 1");
Chart2.Series.Add("Series 2");
// add points to series 1
foreach (int value in (List<int>)ViewData["Chart"])
{
Chart2.Series["Series 1"].Points.AddY(value);
}
// add points to series 2
foreach (int value in (List<int>)ViewData["Chart"])
{
Chart2.Series["Series 2"].Points.AddY(value + 1);
}
Chart2.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
Chart2.BorderColor = System.Drawing.Color.FromArgb(26, 59, 105);
Chart2.BorderlineDashStyle = ChartDashStyle.Solid;
Chart2.BorderWidth = 2;
Chart2.Legends.Add("Legend1");
// Render chart control
Chart2.Page = this;
HtmlTextWriter writer = new HtmlTextWriter(Page.Response.Output);
Chart2.RenderControl(writer);
%>
</p>
Result:
Both controls together:
I think this is a very nice feature (and play well together with ASP.NET MVC) and you could add nice charts without buy a 3rd party licence.


Mahdi Taghizadeh
November 27, 2008
Option B is suitable for MVC approach. Thank you!
Indy
November 28, 2008
Are you sure the new chart controls are based on Dundas? Yes, they are strikingly similar, but, are they really based on the Dundas chart controls?
Robert Muehsig
November 28, 2008
Look at this comment from ScottGu for the relationship between Dundas and the Chart Controls: http://weblogs.asp.net/scottgu/archive/2008/11/24/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt.aspx#6755417
Hollywood
December 4, 2008
I have a problem executing a page with this graphic :
“Error executing child request for ChartImg.axd”
Any idea ?…
Thanks
Hollywood
December 4, 2008
I have this error because of using PARTIAL VIEW PAGE (ascx file)…
But it correctly works with a classic VIEW PAGE (aspx)
Thanks for your help !
Fábio
December 16, 2008
In my machine (Asp.Net Development server) this demo works fine, but when I deploy this demo in IIS 7, i have an error:
[HttpException (0x80004005): Não foi encontrado nenhum manipulador http para o tipo de solicitação 'GET']
  System.Web.HttpApplication.MapIntegratedHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig, Boolean convertNativeStaticFileModule) +824
  System.Web.HttpServerUtility.Execute(String path, TextWriter writer, Boolean preserveForm) +435
[HttpException (0x80004005): Erro ao executar a solicitação filho para ChartImg.axd.]
I have other application Asp.Net MVC running in IIS7, e all works fine, but this demo, don’t work, because MSChart.
I already install MSChart on server.
Anybody help me??? please!!!
Robert Muehsig
December 16, 2008
Have you added the Web.Config settings for the MSCharts?
Fábio
December 16, 2008
Yes, my web.config settings from MSCharts:
<
Â
controls>
<add tagPrefix=”asp” namespace=”System.Web.UI” assembly=”System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″/>
<add tagPrefix=”asp” namespace=”System.Web.UI.WebControls” assembly=”System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″/>
<add tagPrefix=”asp” namespace=”System.Web.UI.DataVisualization.Charting” assembly=”System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/> </controls>
<
Â
httpHandlers>
<remove verb=”*” path=”*.asmx”/>
<add verb=”*” path=”*.asmx” validate=”false” type=”System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″/>
<add verb=”*” path=”*_AppService.axd” validate=”false” type=”System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″/>
<add verb=”GET,HEAD” path=”ScriptResource.axd” type=”System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″ validate=”false”/>
<add verb=”*” path=”*.mvc” validate=”false” type=”System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″/>
<add path=”ChartImg.axd” verb=”GET,HEAD” type=”System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ validate=”false”/>
</httpHandlers>
Work fine on my local machine, but on the server IIS 7 don’t work.
Srinivas
December 18, 2008
Hi,
I am using dotnetnuke. I installed .NET framework 3.5 service pack1 and free Microsoft Chart Controls on my local system. I could develop some charts also but when I deploy that on to the server It does not work it gives an error saying “unknown sever tag asp chart”.My Sever also have windows 2003 service pack 2, .NET framework 3.5 service pack1 and free Microsoft Chart Controls. I observed that my web.config file on local system have some tags(like controls , httphandlers, assemblies) about charts which are missing on server web.config. I made same changes to my server web.config file but nothing worked(I may be doing some wrong in web.config) .Are there any specific settings that must be in web.config file on server ?  Any help is appreciated Thanks in advance.Â
Error:-
DotNetNuke.Services.Exceptions.ModuleLoadException: Unknown server tag ‘asp:Chart’. —> System.Web.HttpParseException: Unknown server tag ‘asp:Chart’. —> System.Web.HttpParseException: Unknown server tagÂ
Parag
December 22, 2008
how to print ASP.net 3.5 chart control any idea
Florian
January 18, 2009
A third option that works very well is to have the following code in your aspx:
<img src=”/Product/GetChart” alt=”Chart” />
This calls the GetChart action on myProduct controller. The action creates a chart in memory, saves the chart as an image to a temp folder and then streams the image of the chart to the client. Btw: the action returns a FileResult.
The main advantage of this third method is that it does not require the aspx page to have any asp server controls and subsequently no code behind is needed.
John Black
January 22, 2009
Florian, could you elaborate on the GetChart controller method? Thanks.
Joel
February 5, 2009
For IIS7, the handler needs to be configured under the system.webServer -> handlers section as
<add name=”ChartHttpHandler” 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″ />
Â
Nic
March 5, 2009
@ John Black
I posted an article at the Codeproject detailing the use of FileResult here: http://www.codeproject.com/KB/aspnet/MvcChartControlFileResult.aspx
If the URL changes the title is:
Streaming Chart images as FileResult from MVC Controllers
Jai
July 28, 2009
I am using MS Charts with MVC in my Program. I want to do a drill down of charts, but due to MVC pattern the chart information from the control to view is JPG. How to do drill down of charts using MS Charts in MVC programming
Ven
August 24, 2009
Try setting the url of the datapoint for drilldown feature :
Chart1.Series[0].Points[0].Url = “”
Karsten Januszewski
March 3, 2010
Code behind in a view is a no no! See this blog post for a way to do charts in a more MVC friendly way:
http://www.codecapers.com/post/Build-a-Dashboard-With-Microsoft-Chart-Controls.aspx
Rajesh Dalvi
March 8, 2010
Hi Robert!
I have found one solution that is very useful and it’s tested in MVC on my side. I have used a part of ur solution B. Follow these steps,
1) Create a partial control. Code of partial control will look like
2) Now call the action and return this view. But the resutl will containg 2 images first blank and next is the desired result. We have to remove the first image using JQuery. So the javascript will look like
$.get(……….,function(data){
$(“#graphOutPut”).html(data);
$(“#aspnetForm img:first”).remove();
});
Thanks for ur help. Keep continuing good work.
Rajesh Dalvi
March 8, 2010
Hi Robert,
I missed the code of partial view in previous comment. Here is the code.
Rajesh Dalvi
March 8, 2010
Hi Robert,
I am not able to put html in comments. So I have commented the html code. Uncomment it for use.
<!–
–>
Rajesh Dalvi
March 8, 2010
Sorry Robert,
I am not able to put html code in comments. Use design time code in partial view and below it, use inline code to generate graph. Last 2 lines are from ur solution B
HtmlTextWriter writer = new HtmlTextWriter(Page.Response.Output);
Chart2.RenderControl(writer);
Let me know whether it’s useful for u or not. Don’t forget about javascript I have included in my previous comments.
paul spence
March 24, 2010
I am using MS charts with a SQL data source and all is working well. The only problem I am currently am having is if my data source returns no data then my chart is just the background colour white. Is there a way of changing this to display a graphic?
Dave Haynes
April 19, 2010
I get this: Session state has created a session id, but cannot save it because the response was already flushed by the application.
Barry Wimlett
April 20, 2010
Also don’t forget to add the routing rules to global.asax to prevent the MVC engine from intercepting the URLS for the Chart httpHandler.
routes.IgnoreRoute(“{controller}/ChartImg.axd”);
routes.IgnoreRoute(“{controller}/{action}/ChartImg.axd”);
If you place the chart control is a view; then the URL for the chart.axd becomes virtualDirectory/ControllerName/MethodName/Chart.axd which of course “conflicts” with the MVC namespace – the result is “broken/missing” images. Unless you add the fix.
wdh
July 21, 2010
Hi,Can you give me a demo for asp.net MVC2.1 with chart control ?Please mail it to me,Thank you!
Rick Roth
July 21, 2010
I was able to successfully get the ChartImg.axd handler to work in an MVC 2 application; however the page’s call to it was resulting in an HTTP 404 error. (I found this using Fiddler.)
It turns out the page was trying to access the handler from /MyController/ChartImg.axd instead of /ChartImg.axd (from the root).
I was able to fix the problem by adding this line to my Global.asax.cs file:
routes.IgnoreRoute(“{controller}/{resource}.axd/{*pathInfo}”);
Prashant Kumar Joshi
November 17, 2010
working fine on local machine but
showing error at server
Parser Error Message: Could not load file or assembly ‘System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′ or one of its dependencies. The system cannot find the file specified.
Source Error:
Line 104:
Line 105:
Line 106:
Line 107:
Line 108:
Source File: D:\Hosting\6134947\html\testingecare\web.config Line: 106
Prashant Kumar Joshi
November 17, 2010
please help
prakash
June 2, 2011
nice post…saves lot my time