In this article we will go step by step to implement Jquery Chart Plugin. Plugin name is Tiny Animated Chart Plugin For jQuery - simple-chart.
I had seen this plugin on www.juqeryscript.net . You can go for detail view of Tiny Animcated Chart plugin at the following link :
http://www.jqueryscript.net/chart-graph/Tiny-Animated-Chart-Plugin-jQuery-simple-chart.html
Additionally you will come to know about the following things:
- About jqueryscript.net
- What is Jquery?
- Step by Step Explanation and Implementation.
About www.jqueryscript.net
JqueryScript.Net is One of the BEST jQuery Plugin websites that provide web designers and developers with a simple way to preview and download a variety of Free jQuery Plugins.
What is Jquery?
Jquery is JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
Step By Step Explanation and Implementation:
STEP 1
Create a new project. File --> New -->Project
Project is named “jquerychart”
STEP 2
STEP 3
Your solution explorer looks like this.
Before we start working on new step, first download a tiny animated chart plugin from given below link:
http://www.jqueryscript.net/chart-graph/Tiny-Animated-Chart-Plugin-jQuery-simple-chart.html
Extract zip file inside “Tiny-Animated-Chart-Plugin-jQuery-simple-chart” folder there are two main files:
- simple-chart.css
Copy this file into CONTENT
- Shimple-chart.js
Copy this file into SCRIPTS
STEP 4
Now we will add a new controller called “InvoiceChart”
Right click on CONTROLLERS folder select ADD --> CONTROLLER
Select “MVC 5 Controller - Empty”
Enter controller name : InvoiceController
STEP 5
Now we move toward to create table and LINQ TO SQL (DBML) file.
Table Structure
- /****** Object: Table [dbo].[tblInvoices] Script Date: 13-Oct-17,Fri 6:48:00 PM ******/
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- CREATE TABLE [dbo].[tblInvoices](
- [InvoiceID] [int] IDENTITY(1,1) NOT NULL,
- [InvoiceDate] [datetime] NULL,
- [ClientName] [nvarchar](50) NULL,
- [ClientZone] [nvarchar](50) NULL,
- [InvoiceAmount] [decimal](18, 0) NULL,
- CONSTRAINT [PK_tblInvoices] PRIMARY KEY CLUSTERED
- (
- [InvoiceID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
Sample Data entry
I entered sample data, you can enter as you require. But follow the same table structure.
SETP 6
Now we are going to set WEB.CONFIG for connection string:
- <connectionStrings>
- <add name="InvoiceConnectionString" connectionString="Data Source=admin;Initial Catalog=MBkTest;Persist Security Info=True;User ID=sa;Password=clserver" providerName="System.Data.SqlClient"/>
- </connectionStrings>
STEP 7
Now we are going to add LINQ TO SQL class (DBML) file.
Right click on project title that is (“jQueryChart”) select ADD --> NEW ITEM
Give the LINQ TO SQL (DBML) file name: “InvoiceDataClasses.dbml”
Now we are going to add tblInvoices in DBML.
Following data is required to generate graph,
Label for titles
- var labels = ["Avatar", "Titanic", "Star Wars: The Force Awakens", "Jurassic World", "Marvel's: The Avengers", "Furious 7", "Avengers: Age of Ultron", "Harry Potter and the Deathly Hallows Part 2", "Frozen", "Iron Man 3"];
Values for generating bars
- var values = [2787965087, 2186772302, 2068223624, 1670400637, 1518812988, 1516045911, 1405403694, 1341511219, 1276480335, 1214811252];
As you see above we required two set of arrays.
STEP 8
Create a viewmodel called INVOICEVIEWMODEL.
Right click on MODEL folder. Select ADD --> Class.
Code of InvoiceViewModel.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace jQueryChart.Models
- {
- public class InvoiceViewModel
- {
- public string ClientName { get; set; }
- public Int32? InvoiceAmount { get; set; }
-
- }
-
- }
Now Go to InvoiceController and code Index Method:
Index Method Code
-
- public ActionResult Index()
- {
- InvoiceDataClassesDataContext db = new InvoiceDataClassesDataContext();
- var salesummary = from a in db.tblInvoices
- group a by a.ClientName into tblInvoice
- select new InvoiceViewModel { ClientName = tblInvoice.Key, InvoiceAmount = tblInvoice.Sum(x => x.InvoiceAmount) };
-
- var SaleTotal = salesummary.ToList().AsEnumerable();
-
- string values = JsonConvert.SerializeObject(SaleTotal.Select(x => x.InvoiceAmount).ToArray());
-
- ViewBag.val = values;
-
- return View(SaleTotal);
- }
STEP 9
Now we are going to create VIEW for index
After selection ADD VIEW option Visual Studio asked details for VIEW
STEP 10
Code of Index.cshtml file
- @using jQueryChart.Models
- @model IEnumerable<jQueryChart.Models.InvoiceViewModel>
-
- @{
- var vals = ViewData["val"] as decimal?[];
- }
- <link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
-
- <!-- Simple Chart CSS file -->
- <link rel="stylesheet" href="~/Content/simple-chart.css">
-
-
- <!-- Start of Chart Render Area-->
- <div class="sc-wrapper">
- <section class="sc-section">
- <div class="column-chart"></div>
- </section>
- <section class="sc-section">
- <div class="bar-chart"></div>
- </section>
- <section class="sc-section">
- <div class="step-chart"></div>
- </section>
- <section class="sc-section">
- <div class="progress-chart"></div>
- </section>
- <section class="sc-section">
- <div class="waterfall-chart"></div>
- </section>
- </div>
- <!-- End of Chart Render Area-->
-
- <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
-
- <!-- Simple Chart JS file -->
- <script src="~/Scripts/simple-chart.js"></script>
-
-
-
- @{
- String clntname = string.Empty;
- }
-
- @{
- ViewBag.Title = "Index";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- <h2>Sales Summary</h2>
-
-
- <table class="table">
- <tr>
-
- <th>
- @Html.DisplayNameFor(model => model.ClientName)
- </th>
- <th>
- Total Sales
- </th>
- </tr>
-
- <!--Creating Array within ForEach Loop -->
- @{
- string name = "[";
- }
- @foreach (var item in Model) {
-
- name = name + "\"" + item.ClientName + "\"";
-
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.ClientName)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.InvoiceAmount)
- </td>
-
- </tr>
- name = name + ",";
- }
- @{
- int fnd = name.Length -1;
- name = name.Substring(0, fnd)+"]";
- }
-
-
- </table>
-
- <input type="hidden" id="hdnfldname" value="@name" />
- <script>
-
-
- function abbreviateNumber(arr) {
- var newArr = [];
- $.each(arr, function (index, value) {
- var newValue = value;
- if (value >= 1000) {
- var suffixes = [" ", " K", " mil", " bil", " t"];
- var suffixNum = Math.floor(("" + value).length / 3);
- var shortValue = '';
- for (var precision = 2; precision >= 1; precision--) {
- shortValue = parseFloat((suffixNum != 0 ? (value / Math.pow(1000, suffixNum)) : value).toPrecision(precision));
- var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g, '');
- if (dotLessShortValue.length <= 2) {
- break;
- }
- }
- if (shortValue % 1 != 0) shortNum = shortValue.toFixed(1);
- newValue = shortValue + suffixes[suffixNum];
- }
- newArr[index] = newValue;
- });
- return newArr;
- }
-
- var labels = JSON.parse('@name'.replace(/"/g,'"'));
- var values = @ViewBag.val;
- var outputValues = abbreviateNumber(values);
-
-
-
- $('.column-chart').simpleChart({
- title: {
- text: 'Column Chart',
- align: 'center'
- },
- type: 'column',
- layout: {
- width: '100%',
- height: '250px'
- },
- item: {
- label: labels,
- value: values,
- outputValue: outputValues,
- color: ['#00aeef'],
- prefix: '$',
- suffix: '',
- render: {
- margin: 0.2,
- size: 'relative'
- }
- }
- });
-
-
- $('.bar-chart').simpleChart({
- title: {
- text: 'Bar Chart',
- align: 'center'
- },
- type: 'bar',
- layout: {
- width: '100%'
- },
- item: {
- label: labels,
- value: values,
- outputValue: outputValues,
- color: ['#00aeef'],
- prefix: '$',
- suffix: '',
- render: {
- margin: 0,
- size: 'relative'
- }
- }
- });
-
- $('.waterfall-chart').simpleChart({
- title: {
- text: 'Waterfall Chart',
- align: 'center'
- },
- type: 'waterfall',
- layout: {
- width: '100%'
- },
- item: {
- label: labels,
- value: values,
- outputValue: outputValues,
- color: ['#00aeef'],
- prefix: '$',
- suffix: '',
- render: {
- margin: 0,
- size: 'absolute'
- }
- }
- });
-
-
- $('.progress-chart').simpleChart({
- title: {
- text: 'Progress Chart',
- align: 'center'
- },
- type: 'progress',
- layout: {
- width: '100%',
- height: '250px'
- },
- item: {
- label: labels,
- value: values,
- outputValue: outputValues,
- color: ['#00aeef'],
- prefix: '$',
- suffix: '',
- render: {
- margin: 0,
- size: 'absolute'
- }
- }
- })
-
- $('.step-chart').simpleChart({
- title: {
- text: 'Step Chart',
- align: 'center'
- },
- type: 'step',
- layout: {
- width: '100%',
- height: '250px'
- },
- item: {
- label: labels,
- value: values,
- outputValue: outputValues,
- color: ['#00aeef'],
- prefix: '$',
- suffix: '',
- render: {
- margin: 0,
- size: 'relative'
- }
- }
- })
- </script>
STEP 11
Now it's time to run the application but before that change the current controller and its action method in ROUTECONFIG.CS
Double click on ROUTECONFIG.CS file
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
-
- namespace jQueryChart
- {
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Invoice", action = "Index", id = UrlParameter.Optional }
- );
- }
- }
- }
As you can see above I had change controller = “Invoice” and action = “Index”.
OUTPUT
You can see Column Chart and Bar Chart.
Step Chart & Progress Chart
Waterfall Chart
Sales Summary