Click here to Skip to main content
15,741,752 members
Articles / Web Development / ASP.NET
Article
Posted 29 Sep 2014

Stats

117.7K views
4.9K downloads
24 bookmarked

Highcharts in asp.net using jquery ajax

Rate me:
Please Sign up or sign in to vote.
4.84/5 (16 votes)
29 Sep 2014CPOL3 min read
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.

C#
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

JavaScript
$(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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer At Lycos Internet Ltd
India India
Amol Jadhao is a ASP.Net Developer
He holds Bachelor's degree in Computer Engineering.
His core skills are ASP.NET,C#.NET,ADO.NET,SQL SERVER,WEB SERVICES,JAVA SCRIPT,JQUERY,AJAX,HTML,CSS.

Comments and Discussions

 
PraiseGreat! Pin
Jliang200820-Oct-17 0:37
Jliang200820-Oct-17 0:37 
QuestionJSON object to Highchart series Pin
shafraz buksh3-Jul-17 18:03
shafraz buksh3-Jul-17 18:03 
Questionpie chart is not displaying Pin
Member 1141149729-May-16 23:03
Member 1141149729-May-16 23:03 
AnswerRe: pie chart is not displaying Pin
Amol Jadhao31-Aug-16 23:11
Amol Jadhao31-Aug-16 23:11 
Questionlinq Pin
super_user12-May-16 20:18
super_user12-May-16 20:18 
AnswerRe: linq Pin
Amol Jadhao31-Aug-16 23:11
Amol Jadhao31-Aug-16 23:11 
QuestionVS 2015 Pin
Member 1227659931-Jan-16 3:52
Member 1227659931-Jan-16 3:52 
AnswerRe: VS 2015 Pin
Amol Jadhao31-Aug-16 23:10
Amol Jadhao31-Aug-16 23:10 
QuestionVery nice sample , tnanks for sharing sample good one Pin
Balaram22418-Jan-16 19:44
professionalBalaram22418-Jan-16 19:44 
QuestionDo you have any example for area-Spline with c# Pin
swap_koki28-Aug-15 2:42
swap_koki28-Aug-15 2:42 
Questioncharts are not loading on the web pages what should i do? Pin
Member 1193084224-Aug-15 1:39
Member 1193084224-Aug-15 1:39 
AnswerRe: charts are not loading on the web pages what should i do? Pin
Member 1193084224-Aug-15 23:09
Member 1193084224-Aug-15 23:09 
GeneralRe: charts are not loading on the web pages what should i do? Pin
Amol Jadhao25-Aug-15 20:00
Amol Jadhao25-Aug-15 20:00 
AnswerRe: charts are not loading on the web pages what should i do? Pin
Amol Jadhao25-Aug-15 19:58
Amol Jadhao25-Aug-15 19:58 
QuestionChart is not displaying Pin
Member 1149543524-Jun-15 6:05
Member 1149543524-Jun-15 6:05 
AnswerRe: Chart is not displaying Pin
Member 1149543526-Jun-15 11:09
Member 1149543526-Jun-15 11:09 
AnswerRe: Chart is not displaying Pin
Member 1193084224-Aug-15 2:06
Member 1193084224-Aug-15 2:06 
QuestionVery Nice Pin
KiranKumar Roy8-Mar-15 21:23
KiranKumar Roy8-Mar-15 21:23 
AnswerRe: Very Nice Pin
Amol Jadhao12-Mar-15 1:19
Amol Jadhao12-Mar-15 1:19 
QuestionHow to implement Drilldown feature Pin
Member 245269816-Feb-15 20:58
Member 245269816-Feb-15 20:58 
QuestionHardcoding data Pin
Member 1139625722-Jan-15 20:08
Member 1139625722-Jan-15 20:08 
AnswerRe: Hardcoding data Pin
Amol Jadhao23-Jan-15 23:13
Amol Jadhao23-Jan-15 23:13 
QuestionHow you called the AJAX Pin
Member 1137660019-Jan-15 0:08
Member 1137660019-Jan-15 0:08 
QuestionTwo series? Pin
Ozan Ozdemiroglu14-Nov-14 8:55
Ozan Ozdemiroglu14-Nov-14 8:55 
AnswerRe: Two series? Pin
Amol Jadhao14-Nov-14 23:39
Amol Jadhao14-Nov-14 23:39 

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.