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:

image_thumb[2]

The best thing is: It should work with ASP.NET MVC!

Download links for the ASP.NET Charts (free) :

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:

image_thumb[4]

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:

image_thumb[6]

Both controls together:

image_thumb[8]

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.

[ Download Source Code ]


If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

About the author

Written by Code Inside Team

Currently there is no additional info about this author.

32 Responses

  1. Option B is suitable for MVC approach. Thank you!

    Reply
  2. 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?

    Reply
  3. 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

    Reply
  4. I have a problem executing a page with this graphic :
    “Error executing child request for ChartImg.axd

    Any idea ?…

    Thanks

    Reply
  5. 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 !

    Reply
  6. 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!!!

    Reply
  7. Have you added the Web.Config settings for the MSCharts?

    Reply
  8. 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.

    Reply
  9. 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 

    Reply
  10. how to print ASP.net 3.5 chart control any idea

    Reply
  11. 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.

    Reply
  12. Florian, could you elaborate on the GetChart controller method? Thanks.

    Reply
  13. 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″ />
     

    Reply
  14. @ 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

    Reply
  15. 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

    Reply
  16. Try setting the url of the datapoint for drilldown feature :

    Chart1.Series[0].Points[0].Url = “”

    Reply
  17. 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

    Reply
  18. 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.

    Reply
  19. Hi Robert,
    I missed the code of partial view in previous comment. Here is the code.

    Reply
  20. Hi Robert,
    I am not able to put html in comments. So I have commented the html code. Uncomment it for use.
    <!–

    –>

    Reply
  21. 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.

    Reply
  22. 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?

    Reply
  23. I get this: Session state has created a session id, but cannot save it because the response was already flushed by the application.

    Reply
  24. 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.

    Reply
  25. Hi,Can you give me a demo for asp.net MVC2.1 with chart control ?Please mail it to me,Thank you!

    Reply
  26. 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}”);

    Reply
  27. 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

    Reply
  28. please help

    Reply
  29. nice post…saves lot my time

    Reply

Comment on this post

Recent Posts

  • image1452_thumb.png
    Javascript to Dart Translator

      Dart, a Google Javascript alternative was presented a few months ago and the web developer scene are a little bit unsure about the usability of Dart. To declare the language Google has translated the Javascript basics into Dart. The result is this “Translator”. In my opinion the name doesn’t find that well because it’s ...

  • image1366-570x194.png
    Twitter Bootstrap as UI-kit

      HTML and CSS are not foreign words for me but I regret, I’m not a Web designer – I see myself as a webdeveloper. But at least a dressy side is a must. But thank good there are some ready “Systems”. Twitter Bootstrap Twitter Bootstrap is a Toolkit for every kind of Web applications. ...

  • image1441.png
    Fix: the value ‚x‘ is not valid for Foo in ASP.NET MVC

      To get files into the MVC Controller Modelbinding from MVC is a clever method. But in fact it is a little bit complicated to set the error message if the connection failed. Example: public class RegisterModel { ... [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email address")] public string Email { get; set; } [Required] [Display(Name = ...

  • You Tube API – recall Video Meta files with .NET

      A loooong time ago I’ve blogged about how to access to You Tube with the Google Data APIs. After all that time there are several new ways how to recall files. Google offers You Tube a “simple” surface. If you prefer to do low-Level HTTP calls it is also possible. Aim: I want the ...

  • image1426-570x194.png
    MacBook Pro for .NET Developer – useful ore just pretty?

      I own a MacBook Pro (from 2010) for about a year now and because I’ve used to think about this Question since I have it, I’m going to blog about my experience now. My Notebook Configurations MacBook Pro April 2010 - 2,66 Intel Core i7 - 8GB RAM - 15’’ Glossy Display - Intel ...

Support us