.NET Technical bits: How to add a Microsoft Chart control to an ASP.NET Page

Tuesday, April 26, 2011

How to add a Microsoft Chart control to an ASP.NET Page

To add charts to a web page simply drag the Chart control from the Toolbox onto the page. Doing so adds the Chart control's declarative mark-up to the page:

<asp:Chart ID="Chart1" runat="server">

<Series>

<asp:Series Name="Series1" IsVisibleInLegend="False">

<EmptyPointStyle IsVisibleInLegend="False" />

</asp:Series>


</Series>


<ChartAreas>


<asp:ChartArea Name="ChartArea1">


</asp:ChartArea>


</ChartAreas>


</asp:Chart>

Note that the Chart control is identified in the declarative mark-up via the tag prefix and name . This prefix (asp) is mapped to the Chart Controls assembly in Web.config:

<controls>


<add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />


</controls>


Additionally, an HTTP Handler named ChartHttpHandler is mapped to requests to chartImg.axd. As we'll see in a bit, when visited through a browser the Chart control renders an <img> element with a src attribute of ChartImg.axd. As a result, the browser makes a request to this file (ChartImg.axd) to display the chart image. This request is routed to the ChartHttpHandler HTTP Handler which generates the image contents and returns that binary data to the browser for display. This mapping between the ChartImg.axd path and the ChartHttpHandler HTTP Handler is implemented via the following Web.config mark-up:

<handlers>

<remove name="ChartImageHandler" />
<add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />


</handlers>

Both of the above configuration additions are automatically added to Web.config when you add a Chart control to a web page for the first time in your project.

No comments:

Post a Comment