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 ]

kick it on DotNetKicks.com

18 Comments so far »

  1. Mahdi Taghizadeh said

    am November 27 2008 @ 8:15 am

    Option B is suitable for MVC approach. Thank you!

  2. Indy said

    am November 28 2008 @ 12:11 am

    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?

  3. Robert Muehsig said

    am November 28 2008 @ 8:34 am

    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

  4. Hollywood said

    am December 4 2008 @ 3:13 pm

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

    Any idea ?…

    Thanks

  5. Hollywood said

    am December 4 2008 @ 5:05 pm

    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 !

  6. Fábio said

    am December 16 2008 @ 12:10 am

    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!!!

  7. Robert Muehsig said

    am December 16 2008 @ 10:42 am

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

  8. Fábio said

    am December 16 2008 @ 2:01 pm

    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.

  9. Srinivas said

    am December 18 2008 @ 5:28 pm

    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 

  10. Parag said

    am December 22 2008 @ 10:58 pm

    how to print ASP.net 3.5 chart control any idea

  11. Florian said

    am January 18 2009 @ 10:46 pm

    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.

  12. John Black said

    am January 22 2009 @ 10:02 pm

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

  13. Joel said

    am February 5 2009 @ 7:10 pm

    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″ />
     

  14. Utilizando biblioteca MS Chart com Asp.net MVC / Monorail « code against the machine said

    am February 27 2009 @ 12:16 am

    [...] já tivesse passado pelos mesmos problemas que eu. Pois bem, nessa busca eu encontrei o seguinte link onde o cara mostra duas maneiras possíveis de se utilizar o componente numa página ASP.Net [...]

  15. Nic said

    am March 5 2009 @ 1:09 pm

    @ 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

  16. ASP.NET MVC, Controles Chart y Ajax… - Burbujas en .NET said

    am April 2 2009 @ 2:36 pm

    [...] Si, como yo, os encanta ASP.NET MVC sabed que podeis usar este control sin ningún problema (http://code-inside.de/blog-in/2008/11/27/howto-use-the-new-aspnet-chart-controls-with-aspnet-mvc/). [...]

  17. Jai said

    am July 28 2009 @ 2:48 pm

    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

  18. Ven said

    am August 24 2009 @ 9:45 pm

    Try setting the url of the datapoint for drilldown feature :

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

Comment RSS · TrackBack URI

Leave a comment

Name: (Required)

eMail: (Required)

Website:

Comment: