Note: This is series of article
In this series we will see one by one in detail about how to draw Chart for Mvc application starting from
You can download the Source Code from this link Download Source Code
In our previous article we have seen in detail about how to draw Bar Chart in MVC web Application. In this article we will see how to draw Line Chart for MVC application using HTML5 Canvas, JQuery, WEB API, and AngularJS.
Our Chart Features
What is the use of Alert Image?
Let’s consider a real time projects. 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.).
7. Save Chart as Image: user can save the chart as Image.
8. 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 numbers of theme as they required.
Blue Theme
Green Theme
In this Article we have 2 parts
Prerequisites
Visual Studio 2015: You can download it from here.
Code Part
In Code part we can see 3 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.
We will create a 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
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB
IF EXISTS (
SELECT
[
name
]
FROM
sys.databases
WHERE
] =
'ItemsDB'
)
DROP
DATABASE
ItemsDB
CREATE
USE ItemsDB
-- 1) //////////// Item Masters
sys.tables
'ItemMaster'
TABLE
ItemMaster
[dbo].[ItemMaster](
[ItemID]
INT
IDENTITY
PRIMARY
KEY
,
[ItemName] [
varchar
](100)
NOT
NULL
[SaleCount] [
](10)
-- insert sample data to Item Master table
INSERT
INTO
ItemMaster ([ItemName],[SaleCount])
VALUES
(
'Item1'
'100'
'Item2'
'82'
'Item3'
'98'
'Item4'
'34'
'Item5'
'68'
select
*
from
-- 1)To Select Item Details
-- Author : Shanu
-- Create date : 2016-03-15
-- Description :To Select Item Details
-- Tables used : ItemMaster
-- Modifier : Shanu
-- Modify date : 2016-03-15
-- =============================================
-- To Select Item Details
-- EXEC USP_Item_Select ''
PROCEDURE
[dbo].[USP_Item_Select]
@ItemName
VARCHAR
(100) =
''
AS
BEGIN
ItemName,
SaleCount
ItemName
like
@ItemName +
'%'
Order
BY
END
-- 2) To Insert/Update Item Details
-- Description :To Insert/Update Item Details
-- To Insert/Update Item Details
-- EXEC USP_Item_Edit ''
[dbo].[USP_Item_Edit]
@SaleCount
(10) =
IF
EXISTS (
ItemName=@ItemName)
(@ItemName,@SaleCount)
Select
'Inserted'
as
results
return
;
ELSE
Update
SET
SaleCount=@SaleCount
ItemName=@ItemName
'Updated'
'Error'
-- 3)To Max and Min Value
-- Description :To Max and Min Value
-- To Max and Min Value
-- EXEC USP_ItemMaxMin_Select ''
[dbo].[USP_ItemMaxMin_Select]
MIN
convert
int
,SaleCount))
MinValue,
MAX
MaxValue
After installing our Visual Studio 2015 click Start, then Programs and select Visual Studio 2015 - Click 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 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 -> New Item.
Select Data->Select ADO.NET Entity Data Model> 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 SQL 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-> 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.
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();
// To get all Item chart detaiuls
[HttpGet]
IEnumerable<USP_Item_Select_Result> getItemDetails(
string
ItemName)
if
(ItemName ==
null
ItemName =
""
objapi.USP_Item_Select(ItemName).AsEnumerable();
}
// To get maximum and Minimum value
IEnumerable<USP_ItemMaxMin_Select_Result> getItemMaxMinDetails(
ItemNM)
(ItemNM ==
ItemNM =
objapi.USP_ItemMaxMin_Select(ItemNM).AsEnumerable();
// To Insert/Update Item Details
IEnumerable<
> insertItem(
itemName,
SaleCount)
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.
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 I given 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.
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”.
// <reference path="../angular.js" />
/// <reference path="../angular.min.js" />
/// <reference path="../angular-animate.js" />
/// <reference path="../angular-animate.min.js" />
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"
($scope, $timeout, $rootScope, $window, $http, FileUploadService) {
$scope.date =
Date();
"RESTClientModule"
($scope, $timeout, $rootScope, $window, $http) {
$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.
// This method is to get all the Item Details to bind in Combobox for plotting in Graph
selectuerRoleDetails($scope.sItemName);
selectuerRoleDetails(ItemName) {
$http.get(
'/api/ItemAPI/getItemDetails/'
, { params: { ItemName: ItemName } }).success(
(data) {
$scope.itemData = data;
$scope.itemCount = $scope.itemData.length;
$scope.selectedItem = $scope.itemData[0].SaleCount;
})
.error(
$scope.error =
"An Error has occured while loading posts!"
});
'/api/ItemAPI/getItemMaxMinDetails/'
, { params: { ItemNM: $scope.sItemName } }).success(
$scope.itemDataMaxMin = data;
$scope.minsnew = $scope.itemDataMaxMin[0].MinValue;
$scope.maxnew = $scope.itemDataMaxMin[0].MaxValue;
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 =
$scope.IsFormSubmitted =
true
$scope.Message =
($scope.ItemNames ==
alert(
"Enter Item Name"
);
($scope.ItemValues ==
) {
"Enter Item Value"
($scope.IsFormValid) {
alert($scope.ItemNames);
'/api/ItemAPI/insertItem/'
, { params: { itemName: $scope.ItemNames, SaleCount: $scope.ItemValues } }).success(
$scope.CharDataInserted = data;
alert($scope.CharDataInserted);
cleardetails();
else
"All the fields are required."
};
Here we will see in detail about how to draw our Line 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
Adding the Chart category colors to array .Here we have fixed to 12 colors and 12 data’s to add with Line 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.
pirChartColor = [
"#6CBB3C"
"#F87217"
"#EAC117"
"#EDDA74"
"#CD7F32"
"#CCFB5D"
"#FDD017"
"#9DC209"
"#E67451"
"#728C00"
"#617C58"
"#64E986"
];
// green Color Combinations
// var pirChartColor = ["#3090C7", "#BDEDFF", "#78C7C7", "#736AFF", "#7FFFD4", "#3EA99F", "#EBF4FA", "#F9B7FF", "#8BB381", "#BDEDFF", "#B048B5", "#4E387E"]; // Blue Color Combinations
//This method will be used to check for user selected Color Theme and Change the color
ChangeChartColor() {
($(
'#rdoColorGreen:checked'
).val() ==
"Green Theme"
lineColor =
"#3090C7"
// Blue Color for Line
lineOuterCircleColor =
// Green Color for Outer Circle
"#BDEDFF"
"#78C7C7"
"#736AFF"
"#7FFFD4"
"#3EA99F"
"#EBF4FA"
"#F9B7FF"
"#8BB381"
"#B048B5"
"#4E387E"
// Blue Color Combinations
// Orange Color for the Line
"#F70D1A "
// Red Color for the outer circle
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.
// This function is used to draw the Legend
drawLengends() {
ctx.fillStyle =
"#7F462C"
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
//Drawing Inner White color Rectange with in Above brown rectangle to plot all the Lables with color,Text and Value.
"#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;
// here to draw all the rectangle for Lables with Image display
$(
'#DropDownList1 option'
).each(
ctx.fillStyle = pirChartColor[colorval];
ctx.fillRect(labelBarX, labelBarY, labelBarWidth, labelBarHeight);
// Here we check for the rdoAlert Status is On - If the Alert is on then we display the Alert Image as per the Alert check value.
'#rdoAlaramOn:checked'
"Alert On"
// Here we can see fo ever chart value we check with the condition .we have initially declare the alertCheckValue as 300.
//so if the Chart Plot value is Greater then or equal to the check value then we display the Green Image else we display the Red Image.
//user can change this to your requiremnt if needed.This is optioan function for the Pie Chart.
(parseInt($(
this
).val()) >= alertCheckValue) {
ctx.drawImage(greenImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);
ctx.drawImage(redImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);
//Draw the Pie Chart Label text and Value
"#000000"
ctx.font =
'10pt Calibri'
ctx.fillText($(
).text(), labelBarX + imagesize + 2, labelBarY + (labelBarHeight / 2));
// To Increment and draw the next bar ,label Text and Alart Image.
labelBarY = labelBarY + labelBarHeight + 4;
// labelTextYXVal = 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 Line chart Method to draw our Line chart inside Canvas Tag.
// This is the main function to darw the Charts
drawChart() {
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.here i 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]'
// 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.
ctx.globalAlpha = 1;
ctx.strokeStyle =
'#000000'
//Every time we clear the canvas and draw the chart
ctx.clearRect(0, 0, canvas.width, canvas.height);
//If need to draw with out legend for the Line Chart
chartWidth = canvas.width - xSpace;
chartHeight = canvas.height - ySpace;
// step 1) Draw legend $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$########################
'#chkLegend:checked'
"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;
//In this method i will draw the legend with the Alert Image.
drawLengends();
// end step 1) $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
chartMidPosition = chartWidth / 2 - 60;
//// //If need to draw with legend
//// chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2));
//// chartHeight = canvas.height - ySpace - 10;
// Step 2 ) +++++++++++++ To Add Chart Titel and Company Logo
//To Add Logo to Chart
logoXVal = canvas.width - LogoImgWidth - 10;
logolYVal = 0;
//here we draw the Logo for teh chart and i have used the alpha to fade and display the Logo.
ctx.globalAlpha = 0.6;
ctx.drawImage(LogoImage, logoXVal, logolYVal, LogoImgWidth, LogoImgHeight);
'22pt Calibri'
"#15317E"
titletxt = $(
'input:text[name=txtTitle]'
ctx.fillText(titletxt, chartMidPosition, chartHeight + 60);
// end step 2) +++++++++++ End of Title and Company Logo Add
// Step 3 ) +++++++++++++ toDraw the X-Axis and Y-Axis
// >>>>>>>>> Draw Y-Axis and X-Axis Line(Horizontal Line)
// Draw the axises
ctx.beginPath();
ctx.moveTo(xSpace, ySpace);
// first Draw Y Axis
ctx.lineTo(xSpace, chartHeight);
// Next draw the X-Axis
ctx.lineTo(chartWidth, chartHeight);
ctx.stroke();
// >>>>>>>>>>>>> End of X-Axis Line Draw
//end step 3) +++++++++++++++++++++++
// Step 4) <<<<<<<<<<<<<<<<<<<<<<< To Draw X - Axis Plot Values <<<<<<<<<<<<< }}}}}}
// Draw the X value texts
// --->>>>>>>>>>>> for the Bar Chart i have draw the X-Axis plot in with drawBarChart
// <<<<<<<<<<<<<<<<<<<<<<< End of X Axis Draw
// end Step 4) <<<<<<<<<<<<<<<<<<<<<<<
// Step 5){{{{{{{{{{{{
// {{{{{{{{{{{{{To Draw the Y Axis Plot Values}}}}}}}}}}}}}}
vAxisPoints = 0;
max = maxDataVal;
max += 10 - max % 10;
for
i = 0; i <= maxDataVal; i += maxValdivValue) {
ctx.fillStyle = fotnColor;
ctx.font = axisfontSize +
'pt Calibri'
ctx.fillText(i, xSpace - 40, getYPlotVale(i));
//Here we draw the Y-Axis point line
ctx.moveTo(xSpace, getYPlotVale(i));
ctx.lineTo(xSpace - 10, getYPlotVale(i));
vAxisPoints = vAxisPoints + maxValdivValue;
//}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
//Step 5) *********************************************************
//Function to Draw our Chart here we can Call/Bar Chart/Line Chart or Pie Chart
drawLineChart();
// end step 6) **************
//Step 7) :::::::::::::::::::: to add the Water mark Text
waterMarktxt = $(
'input:text[name=txtWatermark]'
// Here add the Water mark text at center of the chart
ctx.globalAlpha = 0.1;
'86pt Calibri'
ctx.fillText(waterMarktxt, chartMidPosition - 40, chartHeight / 2);
/// end step 7) ::::::::::::::::::::::::::::::::::::::
In this function we get loop the ComboBox items and get all item Name and Value and draw Line chart and plot values one by one in our Canvas Tag.
drawLineChart()
// For Drawing Line
ctx.lineWidth = 3;
value = $(
'select#DropDownList1 option:selected'
// *************** To Draw the Line and Plot Value in Line
'#FFFFFF'
ctx.moveTo(getXPlotvalue(0), getYPlotVale(value));
'12pt Calibri'
ctx.fillText(value, getXPlotvalue(0), getYPlotVale(value) - 12);
ival = 0;
'#DropDownList1'
).val($(
).eq(0).val());
(i)
(ival > 0)
ctx.lineTo(getXPlotvalue(ival), getYPlotVale($(
).val()));
).val(), getXPlotvalue(ival), getYPlotVale($(
).val()) - 16);
ival = ival + 1;
ctx.fillStyle = lineColor;
ctx.strokeStyle = lineColor;
// *************** To Draw the Line Dot Circle
//For Outer Blue Dot
ctx.fillStyle = lineOuterCircleColor;
ctx.strokeStyle = lineOuterCircleColor;
ctx.arc(getXPlotvalue(ival), getYPlotVale($(
).val()), 7, 0, Math.PI * 2,
ctx.fill();
ctx.fillStyle = lineInnerCircleColor;
ctx.strokeStyle = lineInnerCircleColor;
).val()), 4, 0, Math.PI * 2,
ctx.lineWidth = 1;
Tested Browsers: Chrome , Firefox , IE10
In our previous article we have seen in detail about how to draw Bar Chart in MVC web Application. In this article we will see how to draw Line 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: