AngularJS For Column Series Charting Using MVC 5

Introduction

In this article, we will learn, how to use column series chart, using Web API2, AngularJS, and ADO.NET Framework.

Prerequisites

As I said before, we are going to use jqwidgets plugin in our MVC Application with AngularJS. For this, you must have Visual Studio 2015 (.NET Framework 4.5.2) and SQL Server.

SQL database part

Here, you find the scripts to create the database and the table.

Create database

  1. USE [master]  
  2. GO  
  3.   
  4. /****** Object: Database [DataSys] Script Date: 9/17/2016 8:15:45 AM ******/  
  5. CREATE DATABASE [DataSys]  
  6. CONTAINMENT = NONE  
  7. ON PRIMARY   
  8. NAME = N'DataSys', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DataSys.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  9. LOG ON   
  10. NAME = N'DataSys_log', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DataSys_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  11. GO  
  12.   
  13. ALTER DATABASE [DataSys] SET COMPATIBILITY_LEVEL = 110  
  14. GO  
  15.   
  16. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  17. begin  
  18. EXEC [DataSys].[dbo].[sp_fulltext_database] @action = 'enable'  
  19. end  
  20. GO  
  21.   
  22. ALTER DATABASE [DataSys] SET ANSI_NULL_DEFAULT OFF   
  23. GO  
  24.   
  25. ALTER DATABASE [DataSys] SET ANSI_NULLS OFF   
  26. GO  
  27.   
  28. ALTER DATABASE [DataSys] SET ANSI_PADDING OFF   
  29. GO  
  30.   
  31. ALTER DATABASE [DataSys] SET ANSI_WARNINGS OFF   
  32. GO  
  33.   
  34. ALTER DATABASE [DataSys] SET ARITHABORT OFF   
  35. GO  
  36.   
  37. ALTER DATABASE [DataSys] SET AUTO_CLOSE OFF   
  38. GO  
  39.   
  40. ALTER DATABASE [DataSys] SET AUTO_CREATE_STATISTICS ON   
  41. GO  
  42.   
  43. ALTER DATABASE [DataSys] SET AUTO_SHRINK OFF   
  44. GO  
  45.   
  46. ALTER DATABASE [DataSys] SET AUTO_UPDATE_STATISTICS ON   
  47. GO  
  48.   
  49. ALTER DATABASE [DataSys] SET CURSOR_CLOSE_ON_COMMIT OFF   
  50. GO  
  51.   
  52. ALTER DATABASE [DataSys] SET CURSOR_DEFAULT GLOBAL   
  53. GO  
  54.   
  55. ALTER DATABASE [DataSys] SET CONCAT_NULL_YIELDS_NULL OFF   
  56. GO  
  57.   
  58. ALTER DATABASE [DataSys] SET NUMERIC_ROUNDABORT OFF   
  59. GO  
  60.   
  61. ALTER DATABASE [DataSys] SET QUOTED_IDENTIFIER OFF   
  62. GO  
  63.   
  64. ALTER DATABASE [DataSys] SET RECURSIVE_TRIGGERS OFF   
  65. GO  
  66.   
  67. ALTER DATABASE [DataSys] SET DISABLE_BROKER   
  68. GO  
  69.   
  70. ALTER DATABASE [DataSys] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
  71. GO  
  72.   
  73. ALTER DATABASE [DataSys] SET DATE_CORRELATION_OPTIMIZATION OFF   
  74. GO  
  75.   
  76. ALTER DATABASE [DataSys] SET TRUSTWORTHY OFF   
  77. GO  
  78.   
  79. ALTER DATABASE [DataSys] SET ALLOW_SNAPSHOT_ISOLATION OFF   
  80. GO  
  81.   
  82. ALTER DATABASE [DataSys] SET PARAMETERIZATION SIMPLE   
  83. GO  
  84.   
  85. ALTER DATABASE [DataSys] SET READ_COMMITTED_SNAPSHOT OFF   
  86. GO  
  87.   
  88. ALTER DATABASE [DataSys] SET HONOR_BROKER_PRIORITY OFF   
  89. GO  
  90.   
  91. ALTER DATABASE [DataSys] SET RECOVERY SIMPLE   
  92. GO  
  93.   
  94. ALTER DATABASE [DataSys] SET MULTI_USER   
  95. GO  
  96.   
  97. ALTER DATABASE [DataSys] SET PAGE_VERIFY CHECKSUM   
  98. GO  
  99.   
  100. ALTER DATABASE [DataSys] SET DB_CHAINING OFF   
  101. GO  
  102.   
  103. ALTER DATABASE [DataSys] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )   
  104. GO  
  105.   
  106. ALTER DATABASE [DataSys] SET TARGET_RECOVERY_TIME = 0 SECONDS   
  107. GO  
  108.   
  109. ALTER DATABASE [DataSys] SET READ_WRITE   
  110. GO  
Create table
  1. USE [DataSys]  
  2. GO  
  3.   
  4. /****** Object: Table [dbo].[ChartKEG] Script Date: 9/17/2016 8:16:06 AM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[ChartKEG](  
  15. [ID] [intNOT NULL,  
  16. [Day] [varchar](50) NULL,  
  17. [Keith] [intNULL,  
  18. [Erica] [intNULL,  
  19. [George] [intNULL,  
  20. CONSTRAINT [PK_ChartKEG] PRIMARY KEY CLUSTERED   
  21. (  
  22. [ID] ASC  
  23. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  24. ON [PRIMARY]  
  25.   
  26. GO  
  27.   
  28. SET ANSI_PADDING OFF  
  29. GO  
After creating the table, you can add some records, as shown below-



Create your MVC application

Open Visual Studio and select file, click new project, a new dialog will pop up with the name New Project. Select ASP.NET Web Application (.NET Framework), name your project and click OK button.



Now, new dialog will pop up to select the template. We are going to choose Web API and click OK.



After creating our project, we will proceed to create Web API2 controller.

Create a controller

Now, we are going to create a controller. Right click on the controllers folder > Add > Controller> select Web API 2 Controller – Empty > click Add.



Enter Controller name (‘ChartController’).



ChartController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.SqlClient;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Web.Http;  
  8. using Chart_AngularJS.Models;  
  9.   
  10. namespace Chart_AngularJS.Controllers  
  11. {  
  12.     public class ChartController : ApiController  
  13.     {  
  14.        [HttpGet]  
  15.         public List<ChartModel> GetDataList()  
  16.         {  
  17.   
  18.             SqlConnection conx = new SqlConnection("Data Source=.;Initial Catalog=DataSys;Integrated Security=True");  
  19.   
  20.             conx.Open();  
  21.   
  22.             SqlCommand cmd = new SqlCommand("SELECT * FROM ChartKEG", conx);  
  23.             List<ChartModel> listData = new List<Models.ChartModel>();  
  24.             SqlDataReader dr = cmd.ExecuteReader();  
  25.   
  26.             while (dr.Read())  
  27.             {  
  28.                 ChartModel chart = new Models.ChartModel();  
  29.                 chart.Day = dr[1].ToString();  
  30.                 chart.Keith = int.Parse(dr[2].ToString());  
  31.                 chart.Erica = int.Parse(dr[3].ToString());  
  32.                 chart.George = int.Parse(dr[4].ToString());  
  33.   
  34.                 listData.Add(chart);  
  35.             }  
  36.   
  37.             conx.Close();  
  38.               
  39.   
  40.             return listData;  
  41.         }  
  42.   
  43.     }  
  44. }  
Here, I’m creating GetDataList() action to retrieve all the data from Chart KEG table.

For this action, I’m using ADO.NET framework instead of Entity Framework. First of all, we need to declare SqlConnection object, which allows us to connect to the database (in our case Datasys). We should use SqlCommand object, which takes two parameters respectively , which are query string and connection object. We need to declare SqlDataReader, which receives the records after executing ExecuteReader() method. Finally, we use while to loop all the records.

Here, you find the definition of ChartModel class.

ChartModel.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace Chart_AngularJS.Models  
  7. {  
  8.     public class ChartModel  
  9.     {  
  10.         
  11.         public string Day { get; set; }  
  12.         public int Keith { get; set; }  
  13.         public int Erica { get; set; }  
  14.         public int George { get; set; }  
  15.   
  16.     }  
  17. }   
HomeController.cs
  1. using Chart_AngularJS.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Net.Http;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8.   
  9. namespace Chart_AngularJS.Controllers  
  10. {  
  11.     public class HomeController : Controller  
  12.     {  
  13.         public ActionResult Index()  
  14.         {  
  15.             ViewBag.Title = "Home Page";  
  16.   
  17.             return View();  
  18.         }  
  19.   
  20.         IEnumerable<ChartModel> PopulationList = Enumerable.Empty<ChartModel>();  
  21.   
  22.         [HttpGet]  
  23.         public JsonResult GetChartList()  
  24.         {  
  25.   
  26.             HttpClient client = new HttpClient();  
  27.             client.BaseAddress = new Uri("http://localhost:49487/");  
  28.             client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));  
  29.   
  30.             HttpResponseMessage response = client.GetAsync("api/Chart").Result;  
  31.   
  32.             if (response.IsSuccessStatusCode)  
  33.             {  
  34.                 PopulationList = response.Content.ReadAsAsync<List<ChartModel>>().Result;  
  35.             }  
  36.   
  37.   
  38.             return Json(PopulationList, JsonRequestBehavior.AllowGet);  
  39.   
  40.   
  41.         }  
  42.     }  
  43. }  
As you can see, I am creating GetChartList() action, which calls our API.

To call our API, you need to-
  • Create an object from HttpClient class.
  • Specify URL of our API (in this example, the URL used is: http://localhost:49487/ ).
  • The header of request. I’m choosing application/json, but you can choose another format like XML, CSV etc.
  • Finally, to call API, we need to use GetAsyc("api/Chart"), as mentioned above.

Adding View

In Home controller, just right click on Index() action, select Add view and dialog will pop up.Write a name for your view and finally click Add.



Note - Don’t forget to download the libraries, given below, from jqxwidgets-

  1. <!-- CSS -->  
  2. <link href="~/Content/jqx.base.css" rel="stylesheet" />  
  3. <!-- JS -->  
  4. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>  
  5. <script src="~/Scripts/jqxangular.js"></script>  
  6. <script src="~/Scripts/jqxcore.js"></script>  
  7. <script src="~/Scripts/jqxdata.js"></script>  
  8. <script src="~/Scripts/jqxdraw.js"></script>  
  9. <script src="~/Scripts/jqxchart.core.js"></script>  
Index.cshtml
  1. @{  
  2.     ViewBag.Title = "Home Page";  
  3. }  
  4.   
  5.   
  6. @section scripts{  
  7.   
  8.     <!-- CSS -->  
  9.     <link href="~/Content/jqx.base.css" rel="stylesheet" />  
  10.     <!-- JS -->  
  11.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>  
  12.     <script src="~/Scripts/jqxangular.js"></script>  
  13.     <script src="~/Scripts/jqxcore.js"></script>  
  14.     <script src="~/Scripts/jqxdata.js"></script>  
  15.     <script src="~/Scripts/jqxdraw.js"></script>  
  16.     <script src="~/Scripts/jqxchart.core.js"></script>  
  17.   
  18.     <script type="text/javascript">  
  19.     var demoApp = angular.module("myApp", ["jqwidgets"]);  
  20.         demoApp.controller("ChartCtrl", ['$scope'function ($scope) {  
  21.   
  22.   
  23.   
  24.             //prepare chart data as an array  
  25.             var source = {  
  26.                 datatype: 'json',  
  27.                 datafields: [  
  28.                     { name: 'Day' },  
  29.                     { name: 'Keith' },  
  30.                     { name: 'Erica' },  
  31.                     { name: 'George' }  
  32.                 ],  
  33.                 url: 'GetChartList',  
  34.   
  35.             };  
  36.             var dataAdapter = new $.jqx.dataAdapter(source);  
  37.   
  38.   
  39.             // prepare jqxChart settings  
  40.             var settings = {  
  41.                 title: "Fitness & exercise weekly scorecard",  
  42.                 description: "Time spent in vigorous exercise",  
  43.                 enableAnimations: true,  
  44.                 showLegend: true,  
  45.                 padding: { left: 5, top: 5, right: 5, bottom: 5 },  
  46.                 titlePadding: { left: 90, top: 0, right: 0, bottom: 10 },  
  47.                 source: dataAdapter,  
  48.                 xAxis:  
  49.                     {  
  50.                         dataField: 'Day',  
  51.                         showGridLines: true  
  52.                     },  
  53.                 colorScheme: 'scheme01',  
  54.                 seriesGroups:  
  55.                     [  
  56.                         {  
  57.                             type: 'column',  
  58.                             columnsGapPercent: 50,  
  59.                             seriesGapPercent: 0,  
  60.                             valueAxis:  
  61.                             {  
  62.                                 unitInterval: 10,  
  63.                                 minValue: 0,  
  64.                                 maxValue: 100,  
  65.                                 displayValueAxis: true,  
  66.                                 description: 'Time in minutes',  
  67.                                 axisSize: 'auto',  
  68.                                 tickMarksColor: '#888888'  
  69.                             },  
  70.                             series: [  
  71.                                     { dataField: 'Keith', displayText: 'Keith' },  
  72.                                     { dataField: 'Erica', displayText: 'Erica' },  
  73.                                     { dataField: 'George', displayText: 'George' }  
  74.                                 ]  
  75.                         }  
  76.                     ]  
  77.             };  
  78.   
  79.             $scope.chartSettings = settings;  
  80.         }]);  
  81.     </script>  
  82.   
  83.   
  84. }  
  85.   
  86. <div ng-app="myApp" ng-controller="ChartCtrl">  
  87.   
  88.     <jqx-chart id='chartContainer' jqx-settings="chartSettings" style="width: 850px; height: 500px"></jqx-chart>  
  89.   
  90. </div>  
Output-

Up Next
    Ebook Download
    View all
    Learn
    View all