Introduction
In our previous article we have seen in detail how to draw Bar and Line Chart in MVC web Application. In this article we will see how to draw Pie Chart for MVC application using HTML5 Canvas, JQuery, WEB API and AngularJS.
In this series we will see one-by-one in detail starting from:
- MVC Dynamic Bar Chart using WEB API, AngularJS and JQuery
- MVC Dynamic Line Chart using WEB API, AngularJS and JQuery
- MVC Dynamic Pie Chart using WEB API, AngularJS and JQuery
- MVC Dynamic Line&Bar Chart using WEB API, AngularJS and JQuery
- MVC Dynamic Donut Chart using WEB API, AngularJS and JQuery
- MVC Dynamic Bubble Chart using WEB API, AngularJS and JQuery
Our Chart Features
- Chart Source Data:
Using WEB API and AngularJS we will be loading chart data from database to a Combobox. In our JQuery we will be plotting chart details from the Combobox. - Chart Number of Category:
Chart Items will be dynamically loaded from database. Here we will plot all the Items in Combobox. It’s good to plot less than 12 Items per chart. - Chart Title Text:
User can add their own Chart Title and dynamically change the titles if required. Here in our example we will draw the Title Textbox text at the bottom of the Chart. (You can redesign and customize as per your requirement if needed). - Chart Water Mark Text:
In some cases we need to add our Company name as watermark to our Chart. Here in our example we will draw the watermark Textbox text at the center of the Chart. (You can redesign and customize as per your requirement if needed). - Chart Company LOGO:
User can add own Company logo to the Chart. (Here for sample we have added own image as a Logo at the top left corner. (You can redesign and customize as per your requirement if needed.). - Chart Alert Image Display:
If the “Alert On” radio button is checked we will display the Alert Image. If the “Alert Off” radio button is clicked then the Alert Image will not be displayed. In JQuery we have declared alertCheckValue = 90; and we check the plot data with this aleartcheckValue and if the plot value is greater than this check value then we will display the alert image in the legend.
What is the use of Alert Image?
Let’s consider a real time project. For example, we need to display the chart for a Manufacturing factory with production result as Good and Bad. For example, if production result for each quality value is above 90 we need to display the Alert green Image and if the quality value is below 90 then we need to display the Red Image with label bars.
This Alert Image will be easy to identify each quality result with good or bad. (Here for a sample we have used for quality check and display green and red image, but users can customize as per their requirement and add own image and logics.).
- Save Chart as Image: User can save the chart as Image.
- Chart Theme:
Here we have created 2 themes, Blue and Green for our Chart. We can see both theme output here. User can also add any number of themes as they require.
Blue Theme
Green Theme
In this article we have 2 parts,
- Chart Item and Value Insert/Update to database, Select Chart Item and Value to Combobox from database using WEB API, AngularJS
- Using JQuery Draw our own Chart to HTML5 Canvas tag in our MVC page.
Prerequisites
Visual Studio 2015: You can download it from here .
Code Part
In code part we can see the following three steps,
Step 1: Explains about how to create a sample Database, Table, Stored procedure to select, Insert and Update Chart data to SQL Server.
Step 2: Explains about how to create a WEB API to get the data and bind the result to MVC page using AngularJS.
Step 3: Explains about how to draw our own Chart to our MVC Web application using JQuery.
Step 1: Script to create Table and Stored Procedure
We will create an ItemMaster table under the Database ‘ItemsDB. The following is the script to create a database, table and sample insert query. Run this script in your SQL Server. I have used SQL Server 2014.
- USE MASTER
- GO
-
-
- IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'ItemsDB' )
- DROP DATABASE ItemsDB
- GO
-
- CREATE DATABASE ItemsDB
- GO
-
- USE ItemsDB
- GO
-
-
-
-
- IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'ItemMaster' )
- DROP TABLE ItemMaster
- GO
-
- CREATE TABLE [dbo].[ItemMaster](
- [ItemID] INT IDENTITY PRIMARY KEY,
- [ItemName] [varchar](100) NOT NULL,
- [SaleCount] [varchar](10) NOT NULL
- )
-
-
- INSERT INTO ItemMaster ([ItemName],[SaleCount])
- VALUES ('Item1','100')
-
- INSERT INTO ItemMaster ([ItemName],[SaleCount])
- VALUES ('Item2','82')
-
- INSERT INTO ItemMaster ([ItemName],[SaleCount])
- VALUES ('Item3','98')
-
- INSERT INTO ItemMaster ([ItemName],[SaleCount])
- VALUES ('Item4','34')
-
- INSERT INTO ItemMaster ([ItemName],[SaleCount])
- VALUES ('Item5','68')
-
- select * from ItemMaster
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- CREATE PROCEDURE [dbo].[USP_Item_Select]
- (
- @ItemName VARCHAR(100) = ''
- )
- AS
- BEGIN
- SELECT ItemName,
- SaleCount
- FROM ItemMaster
- WHERE
- ItemName like @ItemName +'%'
- Order BY ItemName
- END
- GO
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- CREATE PROCEDURE [dbo].[USP_Item_Edit]
- (
- @ItemName VARCHAR(100) = '',
- @SaleCount VARCHAR(10) = ''
-
- )
- AS
- BEGIN
- IF NOT EXISTS (SELECT * FROM ItemMaster WHERE ItemName=@ItemName)
- BEGIN
-
- INSERT INTO ItemMaster ([ItemName],[SaleCount])
- VALUES (@ItemName,@SaleCount)
-
- Select 'Inserted' as results
- return;
- END
- ELSE
- BEGIN
- Update ItemMaster SET
- SaleCount=@SaleCount
- WHERE ItemName=@ItemName
- Select 'Updated' as results
- return;
- END
- Select 'Error' as results
- END
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- CREATE PROCEDURE [dbo].[USP_ItemMaxMin_Select]
- (
- @ItemName VARCHAR(100) = ''
- )
- AS
- BEGIN
- SELECT MIN(convert(int,SaleCount)) as MinValue,
- MAX(convert(int,SaleCount)) as MaxValue
- FROM ItemMaster
- WHERE
- ItemName like @ItemName +'%'
-
- END
- GO
Step 2: Create your MVC Web Application in Visual Studio 2015
After installing Visual Studio 2015, click Start, then Programs and select Visual Studio 2015. Click New, then Project, select Web and then select ASP.NET Web Application. Enter your project name and click OK.
Select MVC, Web API and click OK.
Now we have created our MVC Application and as a next step we add our SQL Server database as Entity Data Model to our application.
Add Database using ADO.NET Entity Data Model
Right click our project and click Add, then New Item.
Select Data, ADO.NET Entity Data Model and then give the name for our EF and click Add
Select EF Designer from database and click next.
Here click New Connection and provide your SQL Server - Server Name and connect to your database.
Here we can see we have given our Server name, Id and PWD and after it connected we have selected the data base as ItemsDB as we have created the Database using my SQL Script.
Click next and select our Tables and SP need to be used and click finish.
Once Entity has been created, next step we add WEB API to our controller and write function to Select/Insert/Update and Delete.
Steps to add our WEB API Controller.
Right Click Controllers folder, Click Add and then Controller.
As we are going to create our WEB API Controller select Controller and add Empty WEB API 2 Controller. Give your Name to Web API controller and click OK.
As we all know Web API is a simple and easy to build HTTP Services for Browsers and Mobiles
Web API has four methods as Get/Post/Put and Delete where,
Get is to request for the data. (Select)
Post is to create a data. (Insert)
Put is to update the data.
Delete is to delete data.
In our example we will use both Get and Post as we need to get all image name and descriptions from database and to insert new Image Name and Image Description to database.
Get Method
In our example I have used only Get method as I am using only Stored Procedure. We need to create object for our Entity and write our Get Method to perform Select/Insert/Update and Delete operations.
Select Operation
We use get Method to get all the details of itemMaster table using entity object and we return the result as IEnumerable. We use this method in our AngularJS and bind the result in ComboBox and insert the new chart Item to Database using the Insert Method.
- public class ItemAPIController : ApiController
- {
- ItemsDBEntities objapi = new ItemsDBEntities();
-
-
- [HttpGet]
- public IEnumerable<USP_Item_Select_Result> getItemDetails(string ItemName)
- {
- if (ItemName == null)
- ItemName = "";
- return objapi.USP_Item_Select(ItemName).AsEnumerable();
- }
-
-
- [HttpGet]
- public IEnumerable<USP_ItemMaxMin_Select_Result> getItemMaxMinDetails(string ItemNM)
- {
- if (ItemNM == null)
- ItemNM = "";
- return objapi.USP_ItemMaxMin_Select(ItemNM).AsEnumerable();
- }
-
-
- [HttpGet]
- public IEnumerable<string> insertItem(string itemName, string SaleCount)
- {
- return objapi.USP_Item_Edit(itemName,SaleCount).AsEnumerable();
- }
-
- }
Now we have created our Web API Controller Class. Next step we need to create our AngularJS Module and Controller. Let’s see how to create our AngularJS Controller. In Visual Studio 2015 it’s much easy to add our AngularJS Controller. Let’s see step by step on how to create and write our AngularJS Controller.
Creating AngularJS Controller
Firstly, create a folder inside the Script Folder and give the folder name as “MyAngular”
Now add your Angular Controller inside the folder.
Right Click the MyAngular Folder and click Add and New Item, then select Web and then AngularJS Controller and give name to Controller. We have given my AngularJS Controller as “controller.js”
If the AngularJS package is missing then add the package to your project.
Right Click your MVC project and click Manage NuGet Packages. Search for AngularJS and click Install.
Modules.js:
Here we will add the reference to the AngularJS JavaScript and create an Angular Module named "AngularJs_Module”.
-
-
-
-
- var app;
- (function () {
- app = angular.module("AngularJs_Module", ['ngAnimate']);
- })();
Controllers:
In AngularJS Controller I have done all the business logic and returned the data from Web API to our MVC HTML page.
1. Variable declarations: Firstly, we declared all the local variables need to be used.
- app.controller("AngularJs_Controller", function ($scope, $timeout, $rootScope, $window, $http, FileUploadService) {
- $scope.date = new Date();
-
-
-
-
- var app;
- (function () {
- app = angular.module("RESTClientModule", ['ngAnimate']);
- })();
-
-
- app.controller("AngularJs_Controller", function ($scope, $timeout, $rootScope, $window, $http) {
- $scope.date = new Date();
- $scope.MyName = "shanu";
- $scope.sItemName = "";
- $scope.itemCount = 5;
- $scope.selectedItem = "";
- $scope.chartTitle = "SHANU Line Chart";
- $scope.waterMark = "SHANU";
- $scope.ItemValues = 0;
- $scope.ItemNames = "";
- $scope.showItemAdd = false;
-
- $scope.minsnew = 0;
- $scope.maxnew =0;
2. Methods
Select Method
Here we get all the data from WEB API and bind the result to our ComboBox and we have used another method to get the Maximum and Minimum Value of Chart Value and bind in hidden field.
-
- selectuerRoleDetails($scope.sItemName);
-
- function selectuerRoleDetails(ItemName) {
- $http.get('/api/ItemAPI/getItemDetails/', { params: { ItemName: ItemName } }).success(function (data) {
- $scope.itemData = data;
- $scope.itemCount = $scope.itemData.length;
- $scope.selectedItem = $scope.itemData[0].SaleCount;
-
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
-
- $http.get('/api/ItemAPI/getItemMaxMinDetails/', { params: { ItemNM: $scope.sItemName } }).success(function (data) {
- $scope.itemDataMaxMin = data;
- $scope.minsnew = $scope.itemDataMaxMin[0].MinValue;
- $scope.maxnew = $scope.itemDataMaxMin[0].MaxValue;
-
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
-
- }
Insert Method
User can insert or update Chart Item value by clicking Add Chart Item Details. After validation we pass the Chart Item name and Value to Web API method to insert in to our database.
-
- $scope.saveDetails = function () {
-
- $scope.IsFormSubmitted = true;
-
- $scope.Message = "";
- if ($scope.ItemNames == "")
- {
- alert("Enter Item Name");
- return;
- }
-
- if ($scope.ItemValues == "") {
- alert("Enter Item Value");
- return;
- }
-
-
-
- if ($scope.IsFormValid) {
- alert($scope.ItemNames);
- $http.get('/api/ItemAPI/insertItem/', { params: { itemName: $scope.ItemNames, SaleCount: $scope.ItemValues } }).success(function (data) {
-
- $scope.CharDataInserted = data;
- alert($scope.CharDataInserted);
-
- cleardetails();
- selectuerRoleDetails($scope.sItemName);
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
- }
- else {
- $scope.Message = "All the fields are required.";
- }
- };
- });
Step 3: To draw our Chart using JQuery to our MVC page Canvas Tag
Here we will see in detail how to draw our Pie Chart on our MVC Web Application using JQuery.
Inside JavaScript declare the global variables and initialize the Canvas in JavaScript. In the code I have used comments to easily understand the declarations.
Script Detail Explanations
Script Global variable
Chart Category Color Add
Adding the Chart category colors to array. Here we have fixed to 12 colors and 12 data to add with Pie Chart. If you want you can add more in the code. Here we have 2 set of color combination one with Green base and one with Blue base. User can add as per the requirement here.
- var pirChartColor = ["#6CBB3C", "#F87217", "#EAC117", "#EDDA74", "#CD7F32", "#CCFB5D", "#FDD017", "#9DC209", "#E67451", "#728C00","#617C58", "#64E986"];
-
-
-
- function ChangeChartColor() {
-
- if ($('#rdoColorGreen:checked').val() == "Green Theme") {
- pirChartColor = ["#6CBB3C", "#F87217", "#EAC117", "#EDDA74", "#CD7F32", "#CCFB5D", "#FDD017", "#9DC209","#E67451", "#728C00", "#617C58", "#64E986"];
- lineColor = "#3090C7";
- lineOuterCircleColor = "#6CBB3C";
-
- }
- else {
- pirChartColor = ["#3090C7", "#BDEDFF", "#78C7C7", "#736AFF", "#7FFFD4", "#3EA99F", "#EBF4FA", "#F9B7FF","#8BB381", "#BDEDFF", "#B048B5", "#4E387E"];
- lineColor = "#F87217";
- lineOuterCircleColor = "#F70D1A ";
- }
- }
Draw Legend
If the Show Legend radio button is clicked then we draw a Legend for our Chart item inside Canvas Tag and also in this method we check to display Alert Image or not.
-
- function drawLengends() {
- ctx.fillStyle = "#7F462C";
- ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
-
- ctx.fillStyle = "#FFFFFF";
- rectInner.startX = rect.startX + 1;
- rectInner.startY = rect.startY + 1;
- rectInner.w = rect.w - 2;
- rectInner.h = rect.h - 2;
- ctx.fillRect(rectInner.startX, rectInner.startY, rectInner.w, rectInner.h);
-
-
- labelBarX = rectInner.startX + 4;
- labelBarY = rectInner.startY + 4;
- labelBarWidth = rectInner.w - 10;
- labelBarHeight = (rectInner.h / noOfPlots) - 5;
- colorval = 0;
-
- $('#DropDownList1 option').each(function () {
- ctx.fillStyle = pirChartColor[colorval];
-
- ctx.fillRect(labelBarX, labelBarY, labelBarWidth, labelBarHeight);
-
- if ($('#rdoAlaramOn:checked').val() == "Alert On") {
-
-
-
- if (parseInt($(this).val()) >= alertCheckValue) {
- ctx.drawImage(greenImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);
- }
- else {
- ctx.drawImage(redImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);
- }
- }
-
- ctx.fillStyle = "#000000";
- ctx.font = '10pt Calibri';
- ctx.fillText($(this).text(), labelBarX + imagesize + 2, labelBarY + (labelBarHeight / 2));
-
-
-
- labelBarY = labelBarY + labelBarHeight + 4;
-
-
- colorval = colorval + 1;
-
- });
- }
This is our main function. Here we get all the details to draw our Line Chart. In this function we will draw Chart Titile, Chart Water Mark text, Chart Logo Image and finally call draw Pie chart Method to draw our Pie chart inside Canvas Tag.
-
- function drawChart() {
-
- ChangeChartColor();
-
-
- greenImage.src = '../images/Green.png';
- redImage.src = '../images/Red.png';
-
- LogoImage.src = '../images/shanu.jpg';
-
-
-
- minDataVal = $('input:text[name=hidListMin]').val();
- maxDataVal = $('input:text[name=hidListMax]').val();
-
-
- noOfPlots = $("#DropDownList1 option").length;
-
- maxValdivValue = Math.round((maxDataVal / noOfPlots));
-
-
-
- canvas = document.getElementById("canvas");
- ctx = canvas.getContext("2d");
-
- ctx.globalAlpha = 1;
- ctx.fillStyle = "#000000";
- ctx.strokeStyle = '#000000';
-
- ctx.clearRect(0, 0, canvas.width, canvas.height);
-
-
- chartWidth = canvas.width - xSpace;
- chartHeight = canvas.height - ySpace;
-
-
-
- if ($('#chkLegend:checked').val() == "Show Legend") {
-
- chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2));
- chartHeight = canvas.height - ySpace - 10;
-
- legendWidth = canvas.width - ((canvas.width / 3) - xSpace);
- legendHeight = ySpace;
-
- rect.startX = legendWidth;
- rect.startY = legendHeight;
- rect.w = canvas.width / 3 - xSpace - 10;
- rect.h = canvas.height - ySpace - 10;
-
-
- drawLengends();
-
- }
-
-
- var chartMidPosition = chartWidth / 2 - 60;
-
-
-
-
-
-
-
-
-
-
-
- var logoXVal = canvas.width - LogoImgWidth - 10;
- var logolYVal = 0;
-
-
- ctx.globalAlpha = 0.6;
-
- ctx.drawImage(LogoImage, logoXVal, logolYVal, LogoImgWidth, LogoImgHeight);
-
- ctx.globalAlpha = 1;
-
- ctx.font = '22pt Calibri';
- ctx.fillStyle = "#15317E";
-
- var titletxt = $('input:text[name=txtTitle]').val();
-
- ctx.fillText(titletxt, chartMidPosition, chartHeight + 60);
-
-
- ctx.fillStyle = "#000000";
- ctx.font = '10pt Calibri';
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- drawPieChart();
-
-
-
-
- var waterMarktxt = $('input:text[name=txtWatermark]').val();
-
-
-
- ctx.globalAlpha = 0.1;
- ctx.font = '86pt Calibri';
- ctx.fillStyle = "#000000";
- ctx.fillText(waterMarktxt, chartMidPosition - 40, chartHeight / 2);
-
- ctx.font = '10pt Calibri';
- ctx.globalAlpha = 1;
-
-
- }
In this function we get all item name and value using foreach of ComboBox and here we plot all value and draw Pie Chart using the ComboBox values. Firstly, we will get total of all values from the getChartTotal() Method. We will be using this total value to calculate and draw our Pie Chart.
- function drawPieChart() {
-
- var lastend = 0;
- var XvalPosition = xSpace;
-
- chartWidth = (canvas.width / 2) - xSpace;
- chartHeight = (canvas.height / 2) - (xSpace / 2);
-
- widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots));
-
-
-
- var XLineStartPosition = xSpace;
- var yLineStartPosition = xSpace;
- var yLineHeight = chartHeight;
- var xLineWidth = chartWidth;
-
- colorval = 0;
- var chartTotalResult = getChartTotal();
-
- $('#DropDownList1 option').each(function () {
-
-
- ctx.fillStyle = pirChartColor[colorval];
- ctx.beginPath();
- ctx.moveTo(chartWidth, chartHeight);
-
- ctx.arc(chartWidth, chartHeight + 6, chartHeight, lastend, lastend +
- (Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult)), false);
-
- ctx.lineTo(chartWidth, chartHeight);
-
- ctx.fill();
- lastend += Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult);
-
-
-
- colorval = colorval + 1;
- });
-
-
- }
-
- function getChartTotal() {
- var chartTotalResult = 0;
- $('#DropDownList1 option').each(function () {
-
- chartTotalResult += (typeof parseInt($(this).val()) == 'number') ? parseInt($(this).val()) : 0;
- });
- return chartTotalResult;
- }
NoteRun the SQL Script in your SQL Server to created DB, Table and stored procedure. In web.config change the connection string to your local SQL Server connection. In the attached zip file you can find code for both Bar, Line and Pie Chart.
Tested Browsers
Read more articles on ASP.NET: