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 then select File >> New Website then name it as you wish, I named mine Charts:

class

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:

class

In app Folder:

solution

Step 4

Add the code given below:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. /// <summary>   
  7. /// Summary description for Organisation   
  8. /// </summary>   
  9. public class Marks {  
  10.  
  11.     #region(PRIVATE DATA MEMBERS)  
  12.   
  13.     private int _ID;  
  14.     private string _Name;  
  15.     private string _Subjects;  
  16.     private string _Marks;  
  17.  
  18.     #endregion  
  19.  
  20.  
  21.     #region(PUBLIC DATA MEMBERS)  
  22.   
  23.   
  24.     public int ID {  
  25.         get {  
  26.             return _ID;  
  27.         }  
  28.         set {  
  29.             _ID = value;  
  30.   
  31.         }  
  32.     }  
  33.     public string Name {  
  34.         get {  
  35.             return _Name;  
  36.         }  
  37.         set {  
  38.             _Name = value;  
  39.         }  
  40.   
  41.     }  
  42.     public string Subject {  
  43.         get {  
  44.             return _Subjects;  
  45.         }  
  46.         set {  
  47.             _Subjects = value;  
  48.         }  
  49.   
  50.     }  
  51.     public string Mark {  
  52.   
  53.         get {  
  54.             return _Marks;  
  55.         }  
  56.         set {  
  57.             _Marks = value;  
  58.         }  
  59.   
  60.     }  
  61.  
  62.     #endregion  
  63.   
  64. }  

Step 5

Now add another class MarksDB:

mark

Add the following code to it:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data;  
  6. using System.Data.SqlClient;  
  7.   
  8. /// <summary>   
  9. /// Summary description for MarksDB   
  10. /// </summary>   
  11. public class MarksDB {  
  12.     public MarksDB() {  
  13.         //   
  14.         // TODO: Add constructor logic here   
  15.         //   
  16.     }  
  17.  
  18.     #region(GET Marks LIST)  
  19.   
  20.     public static MarksList GetOrganisations() {  
  21.         MarksList oMarksList = new MarksList();  
  22.         //Change the connection string according to you.  
  23.         using(SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=ak Integrated Security=true")) {  
  24.             con.Open();  
  25.             SqlCommand cmd = new SqlCommand("select * from Marks", con);  
  26.             using(SqlDataReader rdr = cmd.ExecuteReader()) {  
  27.                 while (rdr.Read()) {  
  28.                     oMarksList.Add(FillOragnisation(rdr));  
  29.                 }  
  30.             }  
  31.         }  
  32.   
  33.   
  34.         return oMarksList;  
  35.     }  
  36.  
  37.     #endregion  
  38.  
  39.     #region(FILL Marks)  
  40.   
  41.     public static Marks FillOragnisation(IDataRecord rdr) {  
  42.   
  43.         Marks org = new Marks();  
  44.   
  45.         if (rdr.GetValue(rdr.GetOrdinal("ID")) != DBNull.Value) {  
  46.             org.ID = rdr.GetInt32(rdr.GetOrdinal("ID"));  
  47.         } else {  
  48.             org.ID = -1;  
  49.         }  
  50.         if (rdr.GetValue(rdr.GetOrdinal("Name")) != DBNull.Value) {  
  51.             org.Name = rdr.GetString(rdr.GetOrdinal("Name"));  
  52.         } else {  
  53.             org.Name = string.Empty;  
  54.         }  
  55.         if (rdr.GetValue(rdr.GetOrdinal("Subject")) != DBNull.Value) {  
  56.             org.Subject = rdr.GetString(rdr.GetOrdinal("Subject"));  
  57.         } else {  
  58.             org.Subject = string.Empty;  
  59.         }  
  60.         if (rdr.GetValue(rdr.GetOrdinal("Marks")) != DBNull.Value) {  
  61.             org.Mark = rdr.GetString(rdr.GetOrdinal("Marks"));  
  62.         } else {  
  63.             org.Mark = string.Empty;  
  64.         }  
  65.   
  66.         return org;  
  67.   
  68.     }  
  69.  
  70.     #endregion  
  71. }  
  72.   
  73. (SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=ak Integrated Security=true")).  
  74. 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:

mark list
And add the following code to it:

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Web;   
  5.   
  6. /// <summary>   
  7. /// Summary description for OragnisationList   
  8. /// </summary>   
  9. public class MarksList:List<Marks>   
  10. {   
  11.   
  12. }  

Step 7

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

add web service

After adding the WebService to your project you will have two files:

  1. WebService.asmx and WebService.cs.  

You will find the WebService.cs in the AppCode Folder:

web service

Step 8

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

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  6. using System.Data;  
  7. using System.Data.SqlClient;  
  8.   
  9. /// <summary>   
  10. /// Summary description for WebService   
  11. /// </summary>   
  12. [WebService(Namespace = "http://tempuri.org/")]  
  13. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  14. // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  15. [System.Web.Script.Services.ScriptService]  
  16. public class WebService: System.Web.Services.WebService {  
  17.   
  18.     public WebService() {  
  19.   
  20.         //Uncomment the following line if using designed components   
  21.         //InitializeComponent();   
  22.     }  
  23.   
  24.     [WebMethod]  
  25.     public List < Marks > GetMarksrksList() {  
  26.         try {  
  27.             MarksList oMarksList = new MarksList();  
  28.             oMarksList = MarksDB.GetOrganisations();  
  29.             return oMarksList;  
  30.   
  31.         } catch (Exception EX) {  
  32.             throw EX;  
  33.         }  
  34.   
  35.     }  
  36. }  
  37. //UNCOMMENT THIS LINE FIRST.  
  38.   
  39. [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:

chart aspx

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

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Chart.aspx.cs" Inherits="Chart" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html  
  4.     xmlns="http://www.w3.org/1999/xhtml">  
  5.     <head runat="server">  
  6.         <title></title>  
  7.         <script src="angular.min.js" type="text/javascript"></script>  
  8.         <script src="Chart.min.js" type="text/javascript"></script>  
  9.         <script type="text/javascript">   
  10.   
  11.             var app = angular.module('ChartApp', []);   
  12.             app.controller('ChartController', function ($scope, $http) {   
  13.   
  14.             $scope.FullList = [];   
  15.             $scope.Name = [];   
  16.             $scope.Marks = [];   
  17.   
  18.             GetMarksList();   
  19.             function GetMarksList() {   
  20.   
  21.                 var httrprequest = $http(   
  22.                 {   
  23.                     method: 'POST',   
  24.                     data: '{}',   
  25.                     url: "Services/WebService.asmx/GetMarksrksList" // url to the web method GetMarksList  
  26.                 }).success(function (result) {   
  27.                     $scope.FullList = result.d;   
  28.   
  29.                     for (var i = 0; i < $scope.FullList.length; i++)   
  30.                     {   
  31.                         $scope.Name[i] = $scope.FullList[i].Name;   
  32.                         $scope.Marks[i] = $scope.FullList[i].Mark;   
  33.   
  34.                     }   
  35.                     var data = {  
  36.                        labels: $scope.Name,  
  37.                         datasets: [  
  38.                         {  
  39.                             label: ["Score"],  
  40.                             fillColor: "#F7464A",  
  41.                             strokeColor: "#F7464A",  
  42.                             pointColor: "#F7464A ",  
  43.                             pointStrokeColor: "#fff",  
  44.                             pointHighlightFill: "#fff",  
  45.                             pointHighlightStroke: "rgba(151,187,205,1)",  
  46.                             data: $scope.Marks  
  47.   
  48.                         }]  
  49.                         var ChartAkhil = document.getElementById("ChartBCI").getContext('2d');  
  50.                         new Chart(ChartAkhil).Line(data, Linedefaults);  
  51.   
  52.                     }).error(function (result) {   
  53.   
  54.                          alert("error");   
  55.                      });   
  56.   
  57.                 }   
  58.             });   
  59.   
  60.         </script>  
  61.     </head>  
  62.     <body>  
  63.         <form id="form1" runat="server">  
  64.             <div ng-app="ChartApp" ng-controller="ChartController">  
  65.                 <canvas id="ChartAkhil" height="350" width="350"></canvas>  
  66.             </div>  
  67.         </form>  
  68.     </body>  
  69. </html>   
The following is the code that will provide data to the chart in the canvas:
  1. var data = {  
  2.     labels: $scope.Names, //Providing the name of the students   
  3.     datasets: [{  
  4.         label: ["Score"],  
  5.         fillColor: "#F7464A",  
  6.         strokeColor: "#F7464A",  
  7.         pointColor: "#F7464A ",  
  8.         pointStrokeColor: "#fff",  
  9.         pointHighlightFill: "#fff",  
  10.         pointHighlightStroke: "rgba(151,187,205,1)",  
  11.         data: $scope.Marks //Providing the Data (Marks).  
  12.     }]  
  13.     var ChartAkhil = document.getElementById("ChartBCI").getContext('2d');  
  14.     new Chart(ChartAkhil).Line(data, Linedefaults); //selecting the type of chart you want  
  15.       
We are using a Canvas to show the charts so add it under the form tag:
  1. <form id="form1" runat="server">  
  2.    <div ng-app="ChartApp" ng-controller="ChartController">   
  3.       <canvas id="ChartAkhil" height="350" width="350"></canvas>   
  4.    </div>   
  5. </form>  
Output: Line chart

LINE CHART

Output: Bar Chart

After replacing the Bar with a Line.
  1. var ChartAkhil = document.getElementById("ChartAkhil").getContext('2d');   
  2. new Chart(ChartAkhil).Bar(data);   
chart

 


Similar Articles