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

  • image1528-570x194_thumb.png
    Introduction to Redis on Windows & Redis usage with .NET

      Redis belongs to the NoSQL data banks and you will find it in the group of Key-Value Stores. Redis is often named “Blazing Fast” and according to the Stackoverflow Thread it is used to be two time (while writing) and three times (while reading) quicker than MongoDB. Even if the comparison is a little ...

  • Automated Security Analyser for ASP.NET websites

    Evil Hackers are lurking everywhere and many Web-applications are delicately and share “too much” with the attacker. A quick (first!) overview offers the Tool “ASafaWeb”. All the website does is making a few requests and writing an Analyses including problem solving’s. There are no permanent disadvantages (bad requests/ DoS attacks and so on). Example: KnowYourStack.com ...

  • image1489-570x194.png
    „Sign in with Twitter“ for your own ASP.NET WebApp

      “Sign in with Twitter” is a popular practice to authenticate the users on your website. One advantage compared to an own registration is the lower inhibition for the user. But on the other hand Twitter doesn’t fess up with all the information’s and you will get into a kind of addiction. At the end ...

  • image1485-570x194_thumb.png
    CodePlex is going to be updated

      CodePlex the Microsoft Open Source Project Hosting Plattform hasn’t changed that much in the last few years and for a few times I thought Microsoft stopped the whole developing process. But now I found out that there is still life in the project. Maybe it is because of the success of GitHub or because ...

  • image1474_thumb.png
    What does Adobe in the flash-free web? Magazine-Style Layouts with CSS Regions!

      Adobe is well known for Photoshop and Flash but of course there is a lot more. According to the “Future Post” from Google Adobe declared one of their big subjects on a Blogpost. I’m talking about the W3C Working Draft to CSS Regions. Adobe cooperates with the WebKit Team and W3C on this. What ...

Support us