Jquery Chart Plugin with Asp.Net MVC (Tiny Animated Chart Plugin)
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 on following link :
Additionally you will come to know about following things:
l What is Jquery?
l Step by Step Explanation and Implementation.
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 an new project. File --> New -->Project
Jquery Tutor in Mumbai |
Project Named “jquerychart”
STEP 2
jquery tutor in malad |
STEP 3
Jquery tutor in mumbai |
Your solution explorer look like this.
Before start work on new step, first download tiny animated chart plugin from given below link:
Extract zip file inside “Tiny-Animated-Chart-Plugin-jQuery-simple-chart” folder there is two main files:
1. simple-chart.css: Copy this file into CONTENT folder.
2. Shimple-chart.js: Copy this file into SCRIPTS folder.
STEP 4
Now we will add an new controller called “InvoiceChart”
Right click on CONTROLLERS folder select ADD --> CONTROLLER
Jquery tutor in pune, Jquery Online tutor |
Select “MVC 5 Controller - Empty”
Jquery tutor in Surat, Jquery Tutor in Mumbai |
Enter controller name : InvoiceController
Jquery Tutor in Malad, Kandivali, Borivali, Jquery online tutor |
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:
Sample data I had entered , you can entered as you required. But follow the same table structure.
Jquery tutor in Malad, Jquery tutor in Kandivali |
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
Jquery Tutor in Delhi, Jquery tutor in phalodi |
Give the LINQ TO SQL (DBML) file name: “InvoiceDataClasses.dbml”
Jquery tutor in Malad East, Jquery Tutor in Kandivali West, Jquery online tutor |
Now we are going to add tblInvoices in DBML.
Jquery tutor in kurar village, jquery tutor in malad west, Jquery online tutor |
Following data we 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.
Jquery tutor in maharashtra, Jquery tutor in Andheri |
Jquery tutor in Goregoan, Jquery tutor in jogeshwari |
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:
// GET: Invoice Data
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
jQuery Tutor in Santacruz, Jquery Online tutor |
After selection ADD VIEW option Visual studio asked details for VIEW
Jquery Tutor in Bhayandar, Jquery Tutor in Mira Road |
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>
//this function which convert sales amount into K, milion, bilion ....
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 its 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.
Jquery Tutor in Andheri, Jquery tutor in Mumbai Central |
Step Chart & Progress Chart
Jquery Tutor in Grant Road, Jquery tutor in churchgate |
Waterfall Chart
Jquery Tutor in Baroda, Jquery Tutor in Nashik |
Sales Summary
Jquery Tutor in Dadar, Jquery tutor in prabhadevi |
Happy Coding…
No comments:
Post a Comment