Click here to Skip to main content
15,180,707 members
Articles / Web Development / ASP.NET
Posted 13 Jul 2009


67 bookmarked

Improve ASP.NET Chart with jQuery

Rate me:
Please Sign up or sign in to vote.
4.76/5 (16 votes)
13 Jul 2009CPOL3 min read
A simple example of how to use the ASP.NET charting control with jQuery.

Image 1


This article shows a way to improve ASP.NET charting control capabilities with jQuery. The chart control provided by Microsoft with .NET Framework 3.5 SP1 is a very useful server control with a lot of features. In a real situation, you can have the need to use it client-side, without taking advantage of the ASP.NET server control model. In the example below, I will show a chart that changes based on the selected value in a dropdrown list.


For those who have never heard about it, jQuery is an extremely lightweight and powerful JavaScript library that provides cross-browser compatibility. jQuery popularity among Web developers is growing, to the point that even Microsoft has decided to include it in the ASP.NET MVC framework. On September 2008, Microsoft released the ASP.NET Chart control, a server control to help create graphs of strong visual impact, easy to use, and highly configurable. Here are the prerequisites for using the ASP.NET charting control:

  1. .NET Framework 3.5 SP1
  2. Visual Studio 2008 (SP1 if possible)
  3. Microsoft Chart control
  4. Visual Studio 2008 Tools Support for the Chart control

In addition, you also need:

  1. the latest *.js file of the jQuery JavaScript library (1.3.2 at the time I'm writing)
  2. the jQuery-JSON plug-in available here

Using the Code

Here is the content of the WebSamples project:


  • ChartImageDestructor.cs: contains the definition of CacheItemRemovedCallback
  • RuntimeChart.cs: class that creates the chart object at runtime
  • jquery-1.3.2.min.js: jQuery library script file minified
  • jquery.json-1.3.min.js: the jQuery-JSON plug-in script file minified
  • Default.aspx: test page
  • SampleWebService.asmx: a Web Service that exposes methods called by the client

After decompressing the .zip file, you can create an application under IIS or use the Visual Studio Developer Server. You also must ensure that the TempChartImage folder has the right privileges.

Part 1: Server-Side

First, I create a Web Service in the web application called SampleWebService.asmx. This provides a Web Method DrawChart to render the chart server-side and returns the chart image filename.

/// <summary />
/// Create a chart image and return image file name
/// </summary />
///<param name="iType" /> 
///Type of the chart to draw: 1=Sin(x) 2=Cos(x) 3=Tan(x)
///</param />
public String DrawChart(Int32 iType){

    //class that creates the Chart object
    RuntimeChart runChart = new RuntimeChart();
    Chart m_chart = runChart.makeChart(iType);

    String tempFileName = String.Format("TempChartImage/Chart_{0}.png", 

    tempFileName = Context.Server.MapPath(tempFileName);

    String strImageSrc = @"TempChartImage/" + 

    // set callback when item was removed from cache
    ChartImageDestructor cid = new ChartImageDestructor(tempFileName);
    CacheItemRemovedCallback onRemove = 
       new CacheItemRemovedCallback(cid.RemovedCallback);

    //insert filename into cache
    HttpContext.Current.Cache.Add(tempFileName, cid, null,

    return strImageSrc;

The char image is rendered and saved in the server file system in the TempChartImage directory. The class ChartImageDestructor defines a CacheItemRemovedCallback that is responsible to delete the temp file after a certain elapsed period. The uniqueness of the filename is guaranteed by the function System.Guid.NewGuid() that instantiates a new Globally Unique Identifier.

Part 2: Client-Side

Now, let's take a look at the Default.aspx page. First, I include the script file for jQuery and the jQuery-JSON plug-in.

<script type="text/javascript" src="Script/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="Script/jquery.json-1.3.min.js"></script>

The HTML view contains an img tag and a select element with three options:

           <img id="ChartArea" />
           <select id="graphType">
              <option value="-1">Select type...</option>
              <option value="1">Sin (X)</option>
              <option value="2">Cos (X)</option>
              <option value="3">Tan (X)</option>

Finally, this is the script part with jQuery:

<script type="text/javascript">
   //retrive the URL of the WebService
   var WebServiceURL = "/SampleWebService.asmx";

   //when DOM is ready...
   $(function() {
      //intercept the onchange event fire by element
      //with "graphType" ID (SELECT)
      $("#graphType").change(function() {
         //get the attribute "value" of the OPTION
         //element selected and pass it as parameter
         getChartImage($("option:selected", this).attr("value"));

   function getChartImage(type) {
      if (type < 0)

      //create the object for passing data to Web Service
      var dataPassed = new Object();
      dataPassed.iType = type;

      //call a Web service with jQuery
         type: "POST",
         contentType: "application/json; charset=utf-8",
         url: WebServiceURL + "/DrawChart",
         data: $.toJSON(dataPassed),
              function(msg) {
                 var data = $.evalJSON(msg).d;
                 //set the "src" attribute of image
                 $("#ChartArea").attr("src", data);
              function(XMLHttpRequest, textStatus, errorThrown) {


This example has showed you what these two technologies are able to do using them together. Based on the actual trend in web development to execute a growing quantity of code client-side, it can be expected that situations like these will be more and more frequent. In this scenario, jQuery can give significant help to make client-side development faster and more comprehensible and functional.


  • 10 July 2009 -- Created!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer
Italy Italy
No Biography provided

Comments and Discussions

GeneralNice and helpful article Pin
Member 291674514-Sep-14 17:22
MemberMember 291674514-Sep-14 17:22 
Questionever here of a controller, a view, a model rofl guess not Pin
assholee12-Mar-13 14:33
Memberassholee12-Mar-13 14:33 
QuestionServer side Click Event Pin
samira666-Mar-12 22:14
Membersamira666-Mar-12 22:14 
BugChart is throwing error Pin
MayurikaSoni5-Jul-11 2:12
MemberMayurikaSoni5-Jul-11 2:12 
GeneralMy vote of 3 Pin
rutstyle25-Dec-10 19:49
Memberrutstyle25-Dec-10 19:49 
GeneralRe: My vote of 3 Pin
Malphas198130-Dec-10 5:54
MemberMalphas198130-Dec-10 5:54 
Generalnice code! Pin
talgiladi10-Jul-10 22:37
Membertalgiladi10-Jul-10 22:37 
GeneralRe: nice code! Pin
Malphas198112-Jul-10 0:45
MemberMalphas198112-Jul-10 0:45 
Generalmy post Pin
nørdic13-Jul-09 5:01
Membernørdic13-Jul-09 5:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.