MVC Dynamic Donut Chart Using Web API, AngularJS And JQuery

In our previous article we saw in detail about how to draw Bar, Line, Pie and Bar & Line Chart in MVC web applications. In this article we will see how to draw Donut Chart for MVC application using HTML5 Canvas, JQuery, Web API and AngularJS.

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. (User can redesign and customize as per your requirements if needed).

Chart Water Mark Text:

In some cases we need to add our Company name as Water Mark to our Chart. Here in our example we will draw the Water mark Textbox text at the center of the Chart. (User can redesign and customize as per your requirements if needed).

Chart Company LOGO:

User can add their own Company logo to the Chart.(Here for sample we have added my own image as a Logo at the Top left corner.( User can redesign and customize as per your requirements 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 your requirement and add your 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 outputs here. User can also add any number of themes as they are required.

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.

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 aItemMaster 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.

USEMASTER

GO

-- 1) Check for the Database Exists .If the database is exist then drop and create new DB

Here click New Connection and provide your SQL-Server Server Name and connect to your database.

Here we can see we have given our SQL server name, Id and PWD and after it connectedwe have selected the data base as ItemsDB as we have created the Database using my SQL Script.

Click next and select our tables need to be used and click finish.

Here we can see we have selected our table ItemMasters and all needed Stored Procedures after selecting click Finish,

Once Entity has been created, the next step is 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-> Click 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. Here for my Web API Controller I have given name as “StudentsController”.

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 Deletewhere,

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 names 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.

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 AngularJsController. Let’s see step by Step on how to create and write our AngularJs Controller.

Creating AngularJS Controller

First create a folder inside the Script Folder and we give the folder name as “MyAngular”.

First create a folder inside the Script Folder and Igiven the folder name as “MyAngular”.

Now add your Angular Controller inside the folder.

Right Click the MyAngular Folder and click Add and New Item > Select Web > Select AngularJs Controller and give name to Controller.We have given my AngularJs Controller as “Controller.js”.

If the Angular JS package is missing then add the package to your project.

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.

// This method is to get all the Item Details to bind in Combobox for plotting in Graph

selectuerRoleDetails($scope.sItemName);

// This method is to get all the Item Details to bind in Combobox for plotting in Graph

functionselectuerRoleDetails(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.

//Save File

$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: Todraw our Chart using JQuery to our MVC page Canvas Tag

Herewe will see in detail about how to draw our Donut Chart on our MVC Web Application using JQuery.
Inside the java Script 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’s to add with Donut Chart. If you want you can add more from here. Here we have 2 set of color combination one with Green base and one with Blue base. User can add as per your requirement here.

This is our main Function .Here we get all the details to draw our Donut Chart. In this function we will draw Chart Title, Chart Water Mark text, Chart Logo Image and finally call draw donut chart Method to draw our Donut chart inside Canvas Tag.

// This is the main function to darw the Charts

functiondrawChart()

{

ChangeChartColor();

// asign the images path for both Alert images

greenImage.src = '../images/Green.png';

redImage.src = '../images/Red.png';

LogoImage.src = '../images/shanu.jpg';

// Get the minumum and maximum value.herei have used the hidden filed from code behind wich will stored the Maximum and Minimum value of the Drop down list box.

minDataVal = $('input:text[name=hidListMin]').val();

maxDataVal = $('input:text[name=hidListMax]').val();

// Total no of plots we are going to draw.

noOfPlots = $("#DropDownList1 option").length;

maxValdivValue = Math.round((maxDataVal / noOfPlots));

//storing the Canvas Context to local variable ctx.This variable will be used to draw the Pie Chart

canvas = document.getElementById("canvas");

ctx = canvas.getContext("2d");

//globalAlpha - > is used to display the 100% opoacity of chart .because at the bottom of the code I have used the opacity to 0.1 to display the water mark text with fade effect.

DrawDonutChart:In this function we get all item names and value usingforeachof ComboBoxand here we plot all value and draw Donut chart using the ComboBoxvalues. First we will get total of all values from the getChartTotal() Method. We will be using this total value to calculate and draw our Donut Chart.

Run the SQL Script in your SQL Server to created DB, Table and stored procedure. Inweb.config change the connection string to your local SQL Server connection. In the attached zip file you can find code for both Bar, Line,Pie, Bar& Line and Donut Chart.