Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Highcharts in asp.net using jquery ajax

0.00/5 (No votes)
29 Sep 2014 1  
Looking for a way to draw charts like line,column,bar,pie,area with C#? This is the perfect tutorial for you and its easy to implement.This article will help you to understand how to bind a Pie Chart by calling a web service from jQuery AJAX in ASP.NET

Introduction

Highcharts is a charting library written in pure JavaScript, offering an easy way of adding interactive charts to your web site or web application. Highcharts currently supports line, spline, area, areaspline, column, bar, pie, scatter, angular gauges, arearange, areasplinerange, columnrange, bubble, box plot, error bars, funnel, waterfall and polar chart types.

Main Highchart Features

COMPATIBLE

It works in all modern mobile and desktop browsers including the iPhone/iPad and Internet Explorer from version 6. On iOS and Android, multitouch support provides a seamless user experience.

 OPEN

 One of the key features of Highcharts is that under any of the licenses, free or not, you are allowed to download the source code and make  your own edits. This allows for personal modifications and a great flexibility.


 PURE JAVASCRIPT

Highcharts is solely based on native browser technologies and doesn't require client side plugins like Flash or Java.


 NUMEROUS CHART TYPE

 Highcharts supports line, spline, area, areaspline, column, bar, pie, scatter, angular gauges, arearange, areasplinerange, columnrange and polar chart types. Many of these can be combined in one chart.
 

SIMPLE CONFIGURATION SYNTAX

 Setting the Highcharts configuration options requires no special programming skills. The options are given in a JavaScript object notation structure, which is basically a set of keys and values connected by colons, separated by commas and grouped by curly brackets.


 Export and print

With the exporting module enabled, your users can export the chart to PNG, JPG, PDF or SVG format at the click of a button, or print the chart directly from the web page.

Step 1-Installation

Highcharts requires three files to run, highcharts.js,exporting.js and jquery.min.js.  exporting.js is an optional javascript file for exporting charts. you can download these files from here.

http://www.highcharts.com/download

Step 2-Create table in database

In real time, you may take records from more than one table using joins.Now for this demo,I am creating simple one table in database. We need to design a table in the database to get data from the database.

Table Design

After completion of table design, enter some of the names  and value in the table  to work for our sample.
You can take script.sql file from download folder and execute in database. Now, we will create a web method
in the web service and we will use that method to call it from jQuery. You need to follow the steps given below.

Step 3-Create an ASP.NET Web Service

So add an .asmx page to the current solution and modify the code as in the following exampleusing System.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;//
using System.Data.SqlClient;//
namespace HighchartDemo.Services
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class HighchartService : System.Web.Services.WebService
    {
        public class FruitEnity
        {
            public string Name { get; set; }
            public int Value { get; set; }
        }
        [WebMethod]
        public List<FruitEnity> FruitAnalysis()
        {
            List<FruitEnity> fruitinfo = new List<FruitEnity>();
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection("Data Source=XXXX;User Id=XXXX;
            Password=XXXX;DataBase=XXXX"))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "select name,value from tbl_fruitanalysis";
                    cmd.Connection = con;
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds, "FruitAnalysis");
                    }
                }
            }
            if (ds != null)
            {
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables["FruitAnalysis"].Rows.Count > 0)
                    {
                        foreach (DataRow dr in ds.Tables["FruitAnalysis"].Rows)
                        {
                            fruitinfo.Add(new FruitEnity { Name = dr["name"].ToString(),
                            Value = Convert.ToInt32(dr["value"]) });
                        }
                    }
                }
            }
            return fruitinfo;
        }
    }
}

Step 4-Implement Jquery AJAX

First you need to drag and drop the jQuery library and high library in your ASPX page

  $(document).ready(function () {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Services/HighchartService.asmx/FruitAnalysis",
                data: "{}",
                dataType: "json",
                success: function (Result) {
                    Result = Result.d;
                    var data = [];
                    for (var i in Result) {
                        var serie = new Array(Result[i].Name, Result[i].Value);
                        data.push(serie);
                    }
                    DreawChart(data);
                },
                error: function (Result) {
                    alert("Error");
                }
            });
        });
        function DreawChart(series) {
     
   $('#container').highcharts({

                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: 1, //null,
                    plotShadow: false
                },
                title: {
                    text: 'fruit  market shares at a specific month, 2014'
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                          enabled: true,
                          format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                          style: {
                          color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                            }
                        }
                    }
                },
                series: [{
                    type: 'pie',
                    name: 'Fruit share',
                    data:series
                }]
            });
        }

Output

PieChart

Next article comming soon with drilldrown for column or pi chart.

Points of Interest

 Don't forget to enable the attribute [System.Web.Script.Services.ScriptService], and add the [Web Method] attribute before the function definition in web service.


For highcharts documentation click here  http://api.highcharts.com/highcharts
For highcharts Forum click here  http://forum.highcharts.com
if you looking for DotNet Highchart(write in code behind) click here http://dotnethighcharts.codeplex.com

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here