Implementing Chart.js in ASP.Net Using Angular.js Web Service

This article shows how to implement charts using chart.js in ASP.NET by creating an Angular.js web service. The following is the procedure.

Step 1. First open Visual Studio select File >> New Website then name it as you wish, I named mine Charts.

New Website

Step 2. Now create a table named Marks as in the following.

Table design

Step 3. Add an Entity Class for the Marks table and name it Marks.

 Entity Class

In the app Folder.

App folder

Step 4. Add the code given below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>    
/// Summary description for Organisation    
/// </summary>    
public class Marks {

    #region(PRIVATE DATA MEMBERS)   

    private int _ID;
    private string _Name;
    private string _Subjects;
    private string _Marks;

    #endregion  

    #region(PUBLIC DATA MEMBERS)   

    public int ID {
        get {
            return _ID;
        }
        set {
            _ID = value;

        }
    }
    public string Name {
        get {
            return _Name;
        }
        set {
            _Name = value;
        }

    }
    public string Subject {
        get {
            return _Subjects;
        }
        set {
            _Subjects = value;
        }

    }
    public string Mark {

        get {
            return _Marks;
        }
        set {
            _Marks = value;
        }

    }

    #endregion

}

Step 5. Now add another class MarksDB.

MarksDB

Add the following code to it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

/// <summary>    
/// Summary description for MarksDB    
/// </summary>    
public class MarksDB {
    public MarksDB() {
        //    
        // TODO: Add constructor logic here    
        //    
    }

    #region(GET Marks LIST)   

    public static MarksList GetOrganisations() {
        MarksList oMarksList = new MarksList();
        //Change the connection string according to you.   
        using(SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=ak Integrated Security=true")) {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from Marks", con);
            using(SqlDataReader rdr = cmd.ExecuteReader()) {
                while (rdr.Read()) {
                    oMarksList.Add(FillOragnisation(rdr));
                }
            }
        }


        return oMarksList;
    }

    #endregion   

    #region(FILL Marks)   

    public static Marks FillOragnisation(IDataRecord rdr) {

        Marks org = new Marks();

        if (rdr.GetValue(rdr.GetOrdinal("ID")) != DBNull.Value) {
            org.ID = rdr.GetInt32(rdr.GetOrdinal("ID"));
        } else {
            org.ID = -1;
        }
        if (rdr.GetValue(rdr.GetOrdinal("Name")) != DBNull.Value) {
            org.Name = rdr.GetString(rdr.GetOrdinal("Name"));
        } else {
            org.Name = string.Empty;
        }
        if (rdr.GetValue(rdr.GetOrdinal("Subject")) != DBNull.Value) {
            org.Subject = rdr.GetString(rdr.GetOrdinal("Subject"));
        } else {
            org.Subject = string.Empty;
        }
        if (rdr.GetValue(rdr.GetOrdinal("Marks")) != DBNull.Value) {
            org.Mark = rdr.GetString(rdr.GetOrdinal("Marks"));
        } else {
            org.Mark = string.Empty;
        }

        return org;

    }

    #endregion
}
   
(SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=ak Integrated Security=true")).
Change the connection string according to yo   

Step 6. Now add another class that will return a list of Marks table and name it MarksList.

MarksList

And add the following code to it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>    
/// Summary description for OragnisationList    
/// </summary>    
public class MarksList : List<Marks> {

}

Step 7. Now add a WebService to your website go to Solution Explorer select Add New Folder and name it Services then right-click select Add new item and add a WebService. I named it WebService.asmx.

Solution Explorer

After adding the Web Service to your project you will have two files.

WebService.asmx and WebService.cs.

You will find the web service. cs in the AppCode Folder.

AppCode

Step 8. Now go to the WebService.cs in AppCode and add the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;

/// <summary>    
/// Summary description for WebService    
/// </summary>    
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 WebService: System.Web.Services.WebService {

    public WebService() {

        //Uncomment the following line if using designed components    
        //InitializeComponent();    
    }

    [WebMethod]
    public List< Marks > GetMarksrksList() {
        try {
            MarksList oMarksList = new MarksList();
            oMarksList = MarksDB.GetOrganisations();
            return oMarksList;

        } catch (Exception EX) {
            throw EX;
        }

    }
}
//UNCOMMENT THIS LINE FIRST.   

[System.Web.Script.Services.ScriptService]

So that its methods can be called from the client script.

To invoke a web service method from ECMAScript (JavaScript), you must apply the ScriptServiceAttribute attribute to the related Web service class. When you apply the ScriptServiceAttribute to a Web service class definition that contains one or more methods with WebMethodAttribute applied, the proxy generation script creates a proxy object that corresponds to the Web service class.

Step 9. Download the Chart.js Library from the link given below and include it in your website.

Download the Chart

Step 10. Now download the Angular.min.js Library and include it in your project.

Angular

Step 11. Now add a new WebForm named Chart.aspx.

WebForm

Double-click on Chart.aspx and you will see this window.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Chart.aspx.cs" Inherits="Chart" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="angular.min.js" type="text/javascript"></script>
    <script src="Chart.min.js" type="text/javascript"></script>
    <script type="text/javascript">    

        var app = angular.module('ChartApp', []);
        app.controller('ChartController', function ($scope, $http) {    

        $scope.FullList = [];
        $scope.Name = [];
        $scope.Marks = [];

        GetMarksList();
        function GetMarksList() {

            var httrprequest = $http(
            {
                method: 'POST',
                data: '{}',
                url: "Services/WebService.asmx/GetMarksrksList" // url to the web method GetMarksList  
            }).success(function (result) {
                $scope.FullList = result.d;

                for (var i = 0; i < $scope.FullList.length; i++)
                {
                    $scope.Name[i] = $scope.FullList[i].Name;
                    $scope.Marks[i] = $scope.FullList[i].Mark;

                }
                var data = {
                    labels: $scope.Name,
                    datasets: [
                    {
                        label: ["Score"],
                        fillColor: "#F7464A",
                        strokeColor: "#F7464A",
                        pointColor: "#F7464A ",
                        pointStrokeColor: "#fff",
                        pointHighlightFill: "#fff",
                        pointHighlightStroke: "rgba(151,187,205,1)",
                        data: $scope.Marks

                    }]
                    var ChartAkhil = document.getElementById("ChartBCI").getContext('2d');
                    new Chart(ChartAkhil).Line(data, Linedefaults);

                }).error(function (result) {

                         alert("error");
                     });

                }
            });    

    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div ng-app="ChartApp" ng-controller="ChartController">
            <canvas id="ChartAkhil" height="350" width="350"></canvas>
        </div>
    </form>
</body>
</html>

The following is the code that will provide data to the chart in the canvas.

var data = {
    labels: $scope.Names, //Providing the name of the students    
    datasets: [{
        label: ["Score"],
        fillColor: "#F7464A",
        strokeColor: "#F7464A",
        pointColor: "#F7464A ",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        data: $scope.Marks //Providing the Data (Marks).   
    }]
}
var ChartAkhil = document.getElementById("ChartBCI").getContext('2d');
new Chart(ChartAkhil).Line(data, Linedefaults); //selecting the type of chart you want   

We are using a Canvas to show the charts so add it under the form tag.

<form id="form1" runat="server">   
    <div ng-app="ChartApp" ng-controller="ChartController">   
        <canvas id="ChartAkhil" height="350" width="350"></canvas>   
    </div>   
</form>

Output: Line chart.

LINE CHART

Output: Bar Chart

After replacing the Bar with a Line.

var ChartAkhil = document.getElementById("ChartAkhil").getContext('2d');    
new Chart(ChartAkhil).Bar(data);    

Chart


Similar Articles