Dashboard Application With ASP.NET MVC 5 And jQuery

Introduction

As you know dashboard system has become very important because it helps the managers taking the right decisions. Generally, a dashboard has so many KPIs (Key Performance Indicator) which represent what happens in business. The KPIs or metrics can be number of users, number of orders, top customers, top orders etc...

All of these KPIs give visibility that can allow the top management of any enterprise to make good decisions. In this article, the idea is to build simple dashboard system with KPIs, then represent them in charts (using Google Charts).

Finally, I would like to point out that we will use ASP.NET MVC 5 and jQuery to build our app. I hope you will like it.

Prerequisites

Make sure you have installed Visual Studio 2015 (.NETFramework 4.5.2) and SQL Server.

In this post, we are going to,

  • Create MVC application.
  • Create database (Using Entity Framework Code First).
  • Create controllers (Customer Order, Product, and Dashboard).

Create your MVC application

Open Visual Studio and select File >> New Project.

The "New Project" window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.

ASP.NET

Next, new dialog will pop up for selecting the template. We are going choose MVC template and click Ok.

ASP.NET

Once our project is created, we will create database using entity framework (Code first approach).

SQL Database part

As you know, entity framework has different approach to map database such as database first, model first, and code first. In this article, I’d like to show you how we can create database using code first approach.

Let’s follow the steps below to create our database. Before of all, we are going create Data Access folder.

To do that. From solution explorer >> right click on project name >> Add >> New Folder.

After that, we are adding two new folders, entities and configurations respectively.

Here entities folder contains the definition of all the implied entities in our application whereas configurations folder is used to define characteristics of different properties of each entity.

Entities Folder

Now, we are adding the following entities

IEntity.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace ApplicationDashboardMVC.DataAccess.Entitites  
  8. {  
  9.    public interface IEntity  
  10.     {  
  11.         int ID { get; set; }  
  12.     }  
  13. }  

Customer.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace ApplicationDashboardMVC.DataAccess.Entitites  
  7. {  
  8.     public class Customer : IEntity  
  9.     {  
  10.         public Customer()  
  11.         {  
  12.             Orders = new List<Order>();  
  13.         }  
  14.   
  15.         public int ID { get; set; }  
  16.         public string CustomerName { get; set; }  
  17.         public string CustomerEmail { get; set; }  
  18.         public string CustomerPhone { get; set; }  
  19.         public string CustomerCountry { get; set; }  
  20.         public string CustomerImage { get; set; }  
  21.   
  22.         public virtual ICollection<Order> Orders { get; set; }  
  23.     }  
  24. }  

Order.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace ApplicationDashboardMVC.DataAccess.Entitites  
  7. {  
  8.     public class Order: IEntity  
  9.     {  
  10.         public Order()  
  11.         {  
  12.             OrderDetail = new List<OrderDetails>();  
  13.         }  
  14.         public int ID { get; set; }  
  15.         public DateTime OrderDate { get; set; }  
  16.   
  17.         public virtual Customer Customer { get; set; }  
  18.         public virtual ICollection<OrderDetails> OrderDetail { get; set; }  
  19.     }  
  20. }  

OrderDetails.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace ApplicationDashboardMVC.DataAccess.Entitites  
  7. {  
  8.     public class OrderDetails : IEntity  
  9.     {  
  10.         public int ID { get; set; }  
  11.         public int Quatity { get; set; }  
  12.         public virtual Order Order { get; set; }  
  13.         public virtual Product Product { get; set; }  
  14.     }  
  15. }  

Product.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace ApplicationDashboardMVC.DataAccess.Entitites  
  7. {  
  8.     public class Product : IEntity  
  9.     {  
  10.         public Product()  
  11.         {  
  12.             OrderDetails = new List<OrderDetails>();  
  13.         }  
  14.         public int ID { get; set; }  
  15.         public string ProductName { get; set; }  
  16.         public decimal UnitPrice { get; set; }  
  17.         public int UnitsInStock { get; set; }  
  18.         public string ProductImage { get; set; }  
  19.         public string ProductType { get; set; }  
  20.         public virtual ICollection<OrderDetails> OrderDetails { get; set; }  
  21.           
  22.     }  
  23. }  

Now, it’s time to add configurations of all entities which will be used in our application.

EntityConfiguration.cs

  1. using ApplicationDashboardMVC.DataAccess.Entitites;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data.Entity.ModelConfiguration;  
  5. using System.Linq;  
  6. using System.Web;  
  7.   
  8. namespace ApplicationDashboardMVC.DataAccess.Configurations  
  9. {  
  10.     public class EntityConfiguration<T> : EntityTypeConfiguration<T> where T: class, IEntity  
  11.     {  
  12.         public EntityConfiguration()  
  13.         {  
  14.             HasKey(e=>e.ID);  
  15.         }  
  16.     }  
  17. }  

CustomerConfiguration.cs

  1. using ApplicationDashboardMVC.DataAccess.Entitites;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace ApplicationDashboardMVC.DataAccess.Configurations  
  8. {  
  9.     public class CustomerConfiguration : EntityConfiguration<Customer>  
  10.     {  
  11.         public CustomerConfiguration()  
  12.         {  
  13.             Property(c => c.CustomerName).IsRequired().HasMaxLength(100);  
  14.             Property(c => c.CustomerEmail).IsRequired().HasMaxLength(60);  
  15.             Property(c => c.CustomerPhone).IsRequired().HasMaxLength(100);  
  16.             Property(c => c.CustomerCountry).IsRequired().HasMaxLength(100);  
  17.             Property(c => c.CustomerImage).IsOptional();  
  18.         }  
  19.     }  
  20. }  

OrderConfiguration.cs

  1. using ApplicationDashboardMVC.DataAccess.Entitites;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace ApplicationDashboardMVC.DataAccess.Configurations  
  8. {  
  9.     public class OrderConfiguration : EntityConfiguration<Order>  
  10.     {  
  11.         public OrderConfiguration()  
  12.         {  
  13.             Property(o => o.OrderDate).IsRequired();  
  14.         }  
  15.     }  
  16. }  

OrderDetailsConfiguration.cs

  1. using ApplicationDashboardMVC.DataAccess.Entitites;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace ApplicationDashboardMVC.DataAccess.Configurations  
  8. {  
  9.     public class OrderDetailsConfiguration : EntityConfiguration<OrderDetails>  
  10.     {  
  11.   
  12.         public OrderDetailsConfiguration()  
  13.         {  
  14.             Property(o => o.Quatity).IsRequired();  
  15.         }  
  16.     }  
  17. }  

ProductConfiguration.cs

  1. using ApplicationDashboardMVC.DataAccess.Entitites;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace ApplicationDashboardMVC.DataAccess.Configurations  
  8. {  
  9.     public class ProductConfiguration : EntityConfiguration<Product>  
  10.     {  
  11.         public ProductConfiguration()  
  12.         {  
  13.             Property(p => p.ProductName).IsRequired().HasMaxLength(100);  
  14.             Property(p => p.UnitPrice).IsRequired();  
  15.             Property(p => p.ProductImage).IsRequired().HasMaxLength(100);  
  16.             Property(p => p.UnitsInStock).IsRequired();  
  17.         }  
  18.     }  
  19. }  

As final step. We are adding our dashboard context which will help us to access data from database. Usually context inherits from dbcontext class.

DashboardContext.cs

  1. using ApplicationDashboardMVC.DataAccess.Configurations;  
  2. using ApplicationDashboardMVC.DataAccess.Entitites;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Data.Entity;  
  6. using System.Data.Entity.ModelConfiguration.Conventions;  
  7. using System.Linq;  
  8. using System.Web;  
  9.   
  10. namespace ApplicationDashboardMVC.DataAccess  
  11. {  
  12.     public class DashboardContext : DbContext  
  13.     {  
  14.   
  15.         public DashboardContext():base("DashboardOrder")  
  16.         {  
  17.   
  18.         }  
  19.  
  20.         #region Entities  
  21.         public IDbSet<Customer> CustomerSet { get; set; }  
  22.         public IDbSet<Order> OrderSet { get; set; }  
  23.         public IDbSet<Product> ProductSet { get; set; }  
  24.         public IDbSet<OrderDetails> OrderDetailSet { get; set; }  
  25.  
  26.         #endregion  
  27.   
  28.         protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  29.         {  
  30.             modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();  
  31.   
  32.             modelBuilder.Configurations.Add(new CustomerConfiguration());  
  33.             modelBuilder.Configurations.Add(new OrderConfiguration());  
  34.             modelBuilder.Configurations.Add(new ProductConfiguration());  
  35.             modelBuilder.Configurations.Add(new OrderDetailsConfiguration());  
  36.         }  
  37.   
  38.     }  
  39. }  

Note

Make sure that you have added connection string of your database in Web.config file.

  1. <connectionStrings>  
  2.     <add name="DashboardOrder" connectionString="Data Source=.;Initial Catalog=DashboardOrder;Integrated Security=True" providerName="System.Data.SqlClient" />  
  3.   </connectionStrings>  

Now, Open Package Manager console and type the following command.

Enable-migrations

After that, I can see that we are ready to create our database. Run the following commands respectively.

add-migration "initial_migration"

update-database –verbose

ASP.NET

As you can see above, all the table have been added successfully.

ASP.NET

Create a controller

Now, we are going to create a controller. Right click on the controllers folder> > Add >> Controller>> selecting MVC 5 Controller - Empty>> click Add. In the next dialog name the controller CustomerOrderController and then click Add.

ASP.NET

ASP.NET

CustomerOrderController.cs

  1. using ApplicationDashboardMVC.DataAccess;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace ApplicationDashboardMVC.Controllers  
  9. {  
  10.     public class CustomerOrderController : Controller  
  11.     {  
  12.         // GET: CustomerOrder  
  13.         public ActionResult Index()  
  14.         {  
  15.             return View();  
  16.         }  
  17.   
  18.         [HttpGet]  
  19.         public ActionResult CustomersList()  
  20.         {  
  21.             return View();  
  22.         }  
  23.   
  24.         [HttpGet]  
  25.         public ActionResult GetCustomers()  
  26.         {  
  27.             using (DashboardContext _context = new DashboardContext())  
  28.             {  
  29.                 var customerList = _context.CustomerSet.Select(c => new  
  30.                 {  
  31.                     c.ID,  
  32.                     c.CustomerName,  
  33.                     c.CustomerEmail,  
  34.                     c.CustomerPhone,  
  35.                     c.CustomerCountry,  
  36.                     c.CustomerImage  
  37.                 }).ToList();  
  38.   
  39.                 return Json(new { data = customerList }, JsonRequestBehavior.AllowGet);  
  40.             }  
  41.   
  42.              
  43.         }         
  44.   
  45.     }  
  46. }  

Here, we have added two actions CustomersList decorated with HttpGet attribute and GetCustomers with HttpGet attribute respectively.

CustomersList returns view that contains customer’s datatable whereas GetCustomers retrieves all customers from customer table and returns them in JSON format.

Now, we need to add CustomersList view. To do that, right click on CustomersList action >> Add view >> Add.

CustomersList.cshtml

  1. @{  
  2.     ViewBag.Title = "CustomersList";  
  3. }  
  4.   
  5. <!-- CSS -->  
  6. @*<link href="~/Content/bootstrap.min.css" rel="stylesheet" />*@  
  7. <link href="~/Content/dataTables.bootstrap.min.css" rel="stylesheet" />  
  8.   
  9. <div id="page-wrapper">  
  10.     <div class="row">  
  11.         <div class="col-lg-12">  
  12.             <h1 class="page-header">Customer - Order</h1>  
  13.         </div>  
  14.         <!-- /.col-lg-12 -->  
  15.     </div>  
  16.     <!-- /.row -->  
  17.     <div class="row">  
  18.         <div class="col-lg-12">  
  19.             <div class="panel panel-default">  
  20.                 <div class="panel-heading">  
  21.                     CUSTOMER LIST  
  22.                 </div>  
  23.                 <div class="panel-body">  
  24.                     <div class="row">  
  25.                         <div class="col-lg-12">  
  26.   
  27.                             <table id="myDataTable" class="table table-bordered table-striped table-hover">  
  28.                                 <thead>  
  29.                                     <tr>  
  30.                                         <th>Customer Profil</th>  
  31.                                         <th>Customer ID</th>  
  32.                                         <th>Customer Name</th>  
  33.                                         <th>Customer Email</th>  
  34.                                         <th>Customer Phone</th>  
  35.                                         <th>Customer Country</th>  
  36.                                         <th>Order</th>  
  37.                                          
  38.                                     </tr>  
  39.                                 </thead>  
  40.                             </table>  
  41.   
  42.                         </div>  
  43.                     </div>  
  44.                     <!-- /.row (nested) -->  
  45.                 </div>  
  46.                 <!-- /.panel-body -->  
  47.             </div>  
  48.             <!-- /.panel -->  
  49.         </div>  
  50.         <!-- /.col-lg-12 -->  
  51.     </div>  
  52.     <!-- /.row -->  
  53. </div>  
  54. <!-- /#page-wrapper -->  
  55.   
  56. @section Scripts{  
  57.       
  58. <!-- JS -->  
  59. @*<script src="~/Scripts/jquery-1.10.2.min.js"></script>*@  
  60.     <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>  
  61.     @*<script src="~/Scripts/bootstrap.min.js"></script>*@  
  62.     <script src="~/Scripts/dataTables.bootstrap.min.js"></script>  
  63.   
  64.     <script type="text/javascript">  
  65.   
  66.         $(document).ready(function () {  
  67.   
  68.             //GET DATA FROM DATABASE TO FILL DATATABLE  
  69.             var oTable = $("#myDataTable").DataTable({  
  70.   
  71.                 "ajax": {  
  72.                     "url""/CustomerOrder/GetCustomers",  
  73.                     "type""GET",  
  74.                     "dataType""json"  
  75.                 },  
  76.   
  77.                 "columns": [  
  78.                     {  
  79.                         "data""CustomerImage""width""50px""render"function (data) {  
  80.                             return '<img class="rounded img-thumbnail" style="width:60px; height:58px;" src="/Images/Customers/' + data + '"/>';  
  81.                         }  
  82.                     },  
  83.                     { "data""ID""autowidth"true },  
  84.                     { "data""CustomerName""autowidth"true },  
  85.                     { "data""CustomerEmail""autowidth"true },  
  86.                     { "data""CustomerPhone""autowidth"true },  
  87.                     { "data""CustomerCountry""autowidth"true },  
  88.                     {  
  89.                         "data""ID""width""50px""render"function (data) {  
  90.   
  91.                             return '<a href=/Products/ProductList/'+ data + ' class="btn btn-primary">Order</a>';  
  92.                             //return '<a href=/Products/ProductList/' + data + ' class="btn btn-primary"  data-id= ' + data + '>Order</a>';  
  93.                         }  
  94.                     }  
  95.                 ]  
  96.             });  
  97.   
  98.         });  
  99.   
  100.     </script>  
  101.   
  102. }  

ASP.NET

Notice that, we must add DataTable libraries in order to display customers list into DataTable grid, thus do not forget add the following libraries.

  1. <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>  
  2. <script src="~/Scripts/dataTables.bootstrap.min.js"></script>  

ProductsController.cs

  1. using ApplicationDashboardMVC.DataAccess;  
  2. using ApplicationDashboardMVC.DataAccess.Entitites;  
  3. using ApplicationDashboardMVC.Models;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Data.Entity;  
  7. using System.Globalization;  
  8. using System.Linq;  
  9. using System.Web;  
  10. using System.Web.Mvc;  
  11.   
  12. namespace ApplicationDashboardMVC.Controllers  
  13. {  
  14.     public class ProductsController : Controller  
  15.     {  
  16.   
  17.         public static List<ProductsViewModel> productList = new          List<ProductsViewModel>();  
  18.   
  19.         // GET: Products  
  20.         public ActionResult Index()  
  21.         {  
  22.             return View();  
  23.         }  
  24.   
  25.         [HttpGet]  
  26.         public ActionResult ProductList(int id)  
  27.         {  
  28.             Session["CustomerId"] = id;  
  29.   
  30.             return View();  
  31.         }  
  32.   
  33.         [HttpGet]  
  34.         public ActionResult GetProductByCategory(string category)  
  35.         {  
  36.             using (DashboardContext _context = new DashboardContext())  
  37.             {  
  38.                 List<ProductsViewModel> productList = _context.ProductSet  
  39.                     .Where(p => p.ProductType.ToLower().Equals(category.ToLower()))  
  40.                     .Select(p => new ProductsViewModel  
  41.                         {  
  42.                             ProductID = p.ID,  
  43.                             ProductName = p.ProductName,  
  44.                             UnitPriceProduct = p.UnitPrice,  
  45.                             UnitsInStock = p.UnitsInStock,  
  46.                             ProductImage = p.ProductImage,  
  47.                             ProductType = p.ProductType  
  48.   
  49.                         }).ToList();  
  50.   
  51.                  return PartialView("~/Views/Products/GetProductByCategory.cshtml", productList);  
  52.                   
  53.             }  
  54.     
  55.         }  
  56.   
  57.         [HttpPost]  
  58.         public ActionResult ShoppingCart(ProductsViewModel product)  
  59.         {  
  60.             string message = string.Empty;  
  61.   
  62.             if(product != null)  
  63.             {  
  64.                 productList.Add(product);  
  65.                 message = "product has been added successfully !";  
  66.             }  
  67.             else  
  68.             {  
  69.                 message = "something Wrong  !";  
  70.             }  
  71.               
  72.             return Json( new { message  = message}, JsonRequestBehavior.AllowGet);  
  73.         }  
  74.   
  75.         public ActionResult DisplayShoppingCart()  
  76.         {  
  77.             List<ProductsViewModel> myShoppingCart = productList;  
  78.   
  79.             return PartialView("~/Views/Products/DisplayShoppingCart.cshtml", myShoppingCart);  
  80.         }  
  81.   
  82.          
  83.         [HttpPost]  
  84.         public ActionResult AddOrder(int[] arrIdProduct, int[] arrQteProduct)  
  85.         {  
  86.             int countProduct = arrIdProduct.Length;  
  87.             int customerId = (int)Session["CustomerId"];  
  88.             bool statusTran = false;  
  89.   
  90.             DashboardContext _context = new DashboardContext();  
  91.   
  92.             using (DbContextTransaction dbTran = _context.Database.BeginTransaction())  
  93.             {  
  94.                 try  
  95.                 {  
  96.                     Customer customer = _context.CustomerSet.Find(customerId);  
  97.                     if (customer != null)  
  98.                     {  
  99.                         customer.Orders.Add(new Order { OrderDate = DateTime.Now });  
  100.                     }  
  101.   
  102.                     Order orderSelected = customer.Orders.LastOrDefault();  
  103.   
  104.                     if (orderSelected != null)  
  105.                     {  
  106.                         for (int i = 0; i < countProduct; i++)  
  107.                         {  
  108.                             Product selectedProduct = _context.ProductSet.Find(arrIdProduct[i]);  
  109.                             orderSelected.OrderDetail.Add(new OrderDetails { Product = selectedProduct, Quatity = arrQteProduct[i] });  
  110.                         }  
  111.                     }  
  112.   
  113.                     //Save Changes  
  114.                     int countResult = _context.SaveChanges();  
  115.   
  116.                     //Commit Transaction  
  117.                     dbTran.Commit();  
  118.   
  119.                     if(countProduct > 0)  
  120.                     {  
  121.                         statusTran = true;  
  122.                         productList.Clear();  
  123.                     }  
  124.                       
  125.   
  126.                 }  
  127.                 catch (Exception)  
  128.                 {  
  129.                     dbTran.Rollback();  
  130.                 }  
  131.             }  
  132.   
  133.   
  134.             return Json(new { data = statusTran }, JsonRequestBehavior.AllowGet);  
  135.         }  
  136.   
  137.    
  138.     }  
  139. }  

Let’s explain the different actions implemented within products controller.

ProductList action has an id as parameter which means customer id that would make an order.

Now, we are going add ProductList view. Right click on ProductList action >> Add View >> Add.

ProductList.cshtml

  1. @{  
  2.     ViewBag.Title = "ProductList";  
  3. }  
  4.   
  5. <h2>ProductList</h2>  
  6.   
  7. <div id="page-wrapper">  
  8.     <div class="row">  
  9.         <div class="col-lg-12">  
  10.             <h1 class="page-header">  
  11.                 <span class="glyphicon glyphicon-shopping-cart"></span> Shopping Cart  
  12.                 <p style="display:inline-block; position:relative; right:-56%;">  
  13.                     <button type="button" class="btn btn-primary" id="myOrder">  
  14.                         <span class="glyphicon glyphicon-shopping-cart"></span> My Order   
  15.                     </button>  
  16.                 </p>  
  17.             </h1>  
  18.         </div>  
  19.         <!-- /.col-lg-12 -->  
  20.     </div>  
  21.     <!-- /.row -->  
  22.     <div class="row">  
  23.         <div class="col-lg-12">  
  24.             <div class="panel panel-default">  
  25.                 <div class="panel-heading">  
  26.                     PRODUCT LIST  
  27.                     <div style="display:inline-block; position:relative; right:-68%;">  
  28.                         <button type="button" class="btn btn-primary btn-xs" data-id="Cars">Cars</button>  
  29.                         <button type="button" class="btn btn-default btn-xs" data-id="Clothing">Clothing</button>  
  30.                         <button type="button" class="btn btn-warning btn-xs" data-id="Electronics">Electronics</button>  
  31.                     </div>  
  32.                 </div>  
  33.                 <div class="panel-body">  
  34.   
  35.                     
  36.                 </div> <!-- /.panel-body -->  
  37.                   
  38.             </div>  
  39.             <!-- /.panel -->  
  40.         </div>  
  41.         <!-- /.col-lg-12 -->  
  42.     </div>  
  43.     <!-- /.row -->  
  44. </div>  
  45. <!-- /#page-wrapper -->  
  46.   
  47. <!-- MODAL -->  
  48.   
  49. <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">  
  50.   
  51.     <div class="modal-dialog" role="document">  
  52.   
  53.         <div class="modal-content">  
  54.             <div class="modal-header">  
  55.                 <h4 class="modal-title" id="exampleModalLabel"> <span class="glyphicon glyphicon-shopping-cart"></span> Order </h4>  
  56.                 <button type="button" class="close" data-dismiss="modal" aria-label="Close">  
  57.                     <span aria-hidden="true">×</span>  
  58.                 </button>  
  59.             </div> <!-- MODEL HEADER-->  
  60.   
  61.             <div class="modal-body">  
  62.   
  63.             </div> <!-- MODAL BODY-->  
  64.   
  65.         </div>  
  66.     </div>  
  67.   
  68. </div>  
  69.   
  70.   
  71. @section Scripts{  
  72.       
  73.     <script type="text/javascript">  
  74.   
  75.         $(document).ready(function () {  
  76.   
  77.             $(".btn").click(function (element) {  
  78.   
  79.                 var id = $(this).attr('data-id');  
  80.   
  81.                 $.ajax({  
  82.                     type: 'GET',  
  83.                     url: '@Url.Action("GetProductByCategory", "Products")',  
  84.                     data: { category: $(this).attr('data-id') },  
  85.                     success: function (response) {  
  86.                         $(".panel-body").html(response);  
  87.                     },  
  88.                     error: function (error) {  
  89.   
  90.                     }  
  91.                 });  
  92.   
  93.             });  
  94.   
  95.             $("#myOrder").click(function () {  
  96.   
  97.                 $(".modal-body").html('');  
  98.                 $.ajax({  
  99.   
  100.                     type: 'GET',  
  101.                     url: '@Url.Action("DisplayShoppingCart", "Products")',  
  102.                     success: function (response) {  
  103.   
  104.                         $(".modal-body").html(response);  
  105.                         $("#exampleModal").modal('show');  
  106.   
  107.                     },  
  108.                     error: function () {  
  109.                         alert("Something Wrong");  
  110.                     }  
  111.   
  112.                 });  
  113.             });  
  114.   
  115.         });  
  116.   
  117.     </script>  
  118. }  

ASP.NET

GetProductByCategory accepts category as parameter and it is used to retrieve products from database based on the given category, then display them into GetProductByCategory partial view.

In order to display products by category, we will add new partial view with GetProductByCategory as name.

GetProductByCategory.cshtml

  1. @model IEnumerable<ApplicationDashboardMVC.Models.ProductsViewModel>  
  2. @using ApplicationDashboardMVC.Helpers;  
  3.   
  4. <div class="row">  
  5.   
  6.     @if (Model != null && Model.Any())  
  7.     {  
  8.         foreach (var product in Model)  
  9.         {             
  10.   
  11.             <div class="col-md-4">  
  12.                 <div class="thumbnail">  
  13.   
  14.                     @Html.ProductImage(product.ProductType, product.ProductImage, "300px""165px")  
  15.                       
  16.                     <div class="caption">  
  17.                         <h3 style="text-align:center">@product.ProductName</h3>  
  18.   
  19.                         <span style="position: relative; left: 29%; font-size: 16px;" class="label label-default">  
  20.                             @string.Format("{0} {1}", product.UnitPriceProduct, "$")  
  21.                         </span>  
  22.   
  23.                         <select id="Qte_@product.ProductID" class="form-control" style="margin-top: 10px;">  
  24.                             <option value="1">1</option>  
  25.                             <option value="2">2</option>  
  26.                             <option value="3">3</option>  
  27.                             <option value="4">4</option>  
  28.                             <option value="5">5</option>  
  29.                         </select>  
  30.   
  31.                         <p>  
  32.                             <a class="btn btn-success" id="test" role="button"   
  33.                                data-productId="@product.ProductID"   
  34.                                data-productImage="@product.ProductImage"   
  35.                                data-productName="@product.ProductName"  
  36.                                data-productType="@product.ProductType"  
  37.                                data-UnitPriceProduct="@product.UnitPriceProduct"  
  38.                                style="margin-left: 65px; margin-top: 10px;">  
  39.                                  
  40.                                 <span class="glyphicon glyphicon-shopping-cart"></span>  Add To Card  
  41.                             </a>  
  42.                             @*<button type="button" class="btn btn-success" style="margin-left: 25%; margin-top: 2%;">  
  43.                                 <span class="glyphicon glyphicon-shopping-cart"></span>  Add To Card  
  44.                             </button>*@  
  45.                         </p>  
  46.   
  47.                     </div> <!-- END caption -->  
  48.   
  49.                 </div> <!--END thumbnail-->  
  50.   
  51.             </div> <!-- END col-md-4-->  
  52.             
  53.         }  
  54.   
  55.     }  
  56.   
  57.   
  58.         </div>  
  59. <!-- /.row (nested) -->  
  60.   
  61. <!-- JS -->  
  62.   
  63.       
  64. <script type="text/javascript">  
  65.   
  66.     $(document).ready(function () {  
  67.          
  68.         $('.btn-success').click(function () {  
  69.   
  70.             var selectedProduct = {  
  71.   
  72.                 ProductID: $(this).attr('data-productId'),  
  73.                 ProductImage: $(this).attr('data-productImage'),  
  74.                 ProductName: $(this).attr('data-productName'),  
  75.                 ProductType: $(this).attr('data-productType'),  
  76.                 UnitPriceProduct: $(this).attr('data-UnitPriceProduct'),  
  77.                 QteSelected: $('#Qte_' + $(this).attr('data-productId')).val()  
  78.             };  
  79.   
  80.             console.log(selectedProduct);  
  81.   
  82.             $.ajax({  
  83.                 type: 'POST',  
  84.                 url: '@Url.Action("ShoppingCart", "Products")',  
  85.                 data: selectedProduct,  
  86.                 success: function (response) {  
  87.                     alert(response.message);  
  88.                 },  
  89.                 error: function (response) {  
  90.                     alert(response.message);  
  91.                 }  
  92.                   
  93.             });  
  94.              
  95.         });  
  96.   
  97.         
  98.   
  99.         });  
  100.   
  101. </script>     

ShoppingCart action is used when customers select their products, then they will be added in memory at first this is why we have used productList.

public static List<ProductsViewModel> productList = new List<ProductsViewModel>();

Now, to display all the selected products by customer, we will add DisplayShoppingCart action which is able to show all customer’s products.

So, what we need to do, it’s adding new partial view with DisplayShoppingCart as name then copy-past the following code snippet.

DisplayShoppingCart.cshtml

  1. @model IEnumerable<ApplicationDashboardMVC.Models.ProductsViewModel>  
  2. @using ApplicationDashboardMVC.Helpers;  
  3.   
  4. @{   
  5.     decimal totalOrder = 0;  
  6. }  
  7.   
  8. @if (Model != null && Model.Any())  
  9. {  
  10.     using (Html.BeginForm("AddOrder""Products"new { id = "f"}))  
  11.     {  
  12.     <div class="row">  
  13.   
  14.         <div class="col-md-12">  
  15.             
  16.             <table id="tableOrder" class="table table-hover">  
  17.                 <tr>  
  18.                     <th>Product Image</th>  
  19.                     <th>Product Name</th>  
  20.                     <th>Unit Price</th>  
  21.                     <th>Qte Selected</th>  
  22.                     <th>Product Type</th>  
  23.                     <th>Total Price</th>  
  24.                 </tr>  
  25.                @foreach (var product in Model)  
  26.                {  
  27.                 <tr>  
  28.                     <td>  
  29.                        @Html.ProductImage(product.ProductType, product.ProductImage, "60px""58px")  
  30.                     </td>  
  31.                     <td>@product.ProductName</td>  
  32.                     <td>@string.Format("{0} $", product.UnitPriceProduct)</td>  
  33.                     <td>@product.QteSelected</td>  
  34.                     <td>@ProductType(product.ProductType)</td>  
  35.                     <td>@string.Format("{0} $", (product.UnitPriceProduct * product.QteSelected))</td>  
  36.                 </tr>  
  37.                    totalOrder += (product.QteSelected * product.UnitPriceProduct);  
  38.   
  39.                 @Html.HiddenFor(p=>product.ProductID)  
  40.                 @Html.HiddenFor(p => product.QteSelected)  
  41.   
  42.                }  
  43.             </table>  
  44.   
  45.             <!-- TOTAL PRICE-->  
  46.             <h4 style="margin-left: 66%;">Total : <span class="label label-info">@string.Format("{0} $", totalOrder)</span></h4>  
  47.         </div>  
  48.     </div>  
  49.   
  50.     <div class="modal-footer">  
  51.         <button type="button" class="btn btn-secondary" id="close" data-dismiss="modal">Close</button>  
  52.         <button type="button" class="btn btn-primary" id="SaveOrder">Save Order</button>  
  53.     </div> <!-- MODAL FOOTER-->  
  54.         }  
  55.     }  
  56. else  
  57. {  
  58.     <div class="alert alert-warning" role="alert"> your basket is empty !</div>  
  59. }  
  60.   
  61.   
  62. <!-- HELPER -->  
  63.   
  64. @helper ProductType(string productType) {  
  65.   
  66.     switch (productType)  
  67.     {  
  68.         case "Cars":  
  69.                 <span class="label label-success">@productType</span>  
  70.             break;  
  71.         case "Clothing":  
  72.                 <span class="label label-warning">@productType</span>  
  73.             break;  
  74.         case "Electronics":  
  75.                 <span class="label label-info">@productType</span>  
  76.             break;  
  77.     }  
  78. }  
  79.   
  80. <!--JS-->  
  81.   
  82. <script type="text/javascript">  
  83.   
  84.     $(document).ready(function () {  
  85.   
  86.         //add class rounded img-thumbnail to img tag  
  87.         $('img').addClass('rounded img-thumbnail');  
  88.   
  89.         //Save Order  
  90.         $("#SaveOrder").click(function () {  
  91.   
  92.             var $form = $(this).closest('form');  
  93.             var dataProduct = $form.serializeArray();  
  94.   
  95.             console.log(dataProduct);  
  96.   
  97.             var arrIdProduct = [];  
  98.             var arrQteProduct = [];  
  99.   
  100.             for( i = 0; i < dataProduct.length; i++)  
  101.             {  
  102.                 if (dataProduct[i].name == 'product.ProductID')  
  103.                 {  
  104.                     arrIdProduct.push(dataProduct[i].value);  
  105.                 }  
  106.                 else if (dataProduct[i].name == 'product.QteSelected')  
  107.                 {  
  108.                     arrQteProduct.push(dataProduct[i].value);  
  109.   
  110.                 }  
  111.             }  
  112.   
  113.             $.ajax({  
  114.                 type: 'POST',  
  115.                 url: '@Url.Action("AddOrder", "Products")',  
  116.                 data: { arrIdProduct, arrQteProduct },  
  117.                 success: function (response) {  
  118.                     if(response.data == true)  
  119.                     {  
  120.                         alert("Order has saved successfully ");  
  121.                     }  
  122.                     else  
  123.                     {  
  124.                         alert("Something Wrong ! ");  
  125.                     }  
  126.   
  127.                 },  
  128.                 error: function (error) {  
  129.                     alert("Something Wrong ! ");  
  130.                 }  
  131.             });  
  132.         });  
  133.   
  134.     });  
  135.   
  136. </script>  

ASP.NET

Finally, AddOrder action is responsible to add new order with different products which are included to it.

Now, let's take a look at DashboardController

DashboardController.cs

  1. using ApplicationDashboardMVC.DataAccess;  
  2. using ApplicationDashboardMVC.Models;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8.   
  9. namespace ApplicationDashboardMVC.Controllers  
  10. {  
  11.     public class DashboardController : Controller  
  12.     {  
  13.         // GET: Dashboard  
  14.         public ActionResult Index()  
  15.         {  
  16.             return View();  
  17.         }  
  18.   
  19.         public ActionResult Dashboard()  
  20.         {  
  21.   
  22.             using (DashboardContext _context = new DashboardContext())  
  23.             {  
  24.                 ViewBag.CountCustomers = _context.CustomerSet.Count();  
  25.                 ViewBag.CountOrders = _context.OrderSet.Count();  
  26.                 ViewBag.CountProducts = _context.ProductSet.Count();  
  27.             }  
  28.   
  29.            return View();  
  30.         }  
  31.   
  32.         public ActionResult GetDetails(string type)  
  33.         {  
  34.             List<ProductOrCustomerViewModel> result = GetProductOrCustomer(type);  
  35.   
  36.             return PartialView("~/Views/Dashboard/GetDetails.cshtml", result);  
  37.   
  38.         }  
  39.   
  40.   
  41.         public ActionResult TopCustomers()  
  42.         {  
  43.             List<TopCustomerViewModel> topFiveCustomers = null;  
  44.             using (DashboardContext _context = new DashboardContext())  
  45.             {  
  46.                 var OrderByCustomer = (from o in _context.OrderSet  
  47.                                       group o by o.Customer.ID into g  
  48.                                       orderby g.Count() descending  
  49.                                       select new  
  50.                                       {  
  51.                                          CustomerID = g.Key,  
  52.                                          Count = g.Count()  
  53.                                       }).Take(5);  
  54.   
  55.                  topFiveCustomers = (from c in _context.CustomerSet  
  56.                                   join o in OrderByCustomer  
  57.                                   on c.ID equals o.CustomerID  
  58.                                   select new TopCustomerViewModel  
  59.                                   {  
  60.                                       CustomerName = c.CustomerName,  
  61.                                       CustomerImage = c.CustomerImage,  
  62.                                       CustomerCountry = c.CustomerCountry,  
  63.                                       CountOrder = o.Count  
  64.                                   }).ToList();  
  65.             }  
  66.   
  67.             return PartialView("~/Views/Dashboard/TopCustomers.cshtml", topFiveCustomers);  
  68.         }  
  69.   
  70.         public ActionResult OrdersByCountry()  
  71.         {  
  72.             DashboardContext _context = new DashboardContext();  
  73.               
  74.              var ordersByCountry = (from o in _context.OrderSet  
  75.                                        group o by o.Customer.CustomerCountry into g  
  76.                                        orderby g.Count() descending  
  77.                                        select new  
  78.                                        {  
  79.                                            Country = g.Key,  
  80.                                            CountOrders = g.Count()  
  81.                                        }).ToList();  
  82.               
  83.             return Json(new { result = ordersByCountry }, JsonRequestBehavior.AllowGet);  
  84.         }  
  85.   
  86.         public ActionResult CustomersByCountry()  
  87.         {  
  88.             DashboardContext _context = new DashboardContext();  
  89.   
  90.             var customerByCountry = (from c in _context.CustomerSet  
  91.                                    group c by c.CustomerCountry into g  
  92.                                    orderby g.Count() descending  
  93.                                    select new  
  94.                                    {  
  95.                                        Country = g.Key,  
  96.                                        CountCustomer = g.Count()  
  97.                                    }).ToList();  
  98.   
  99.             return Json(new { result = customerByCountry }, JsonRequestBehavior.AllowGet);  
  100.         }  
  101.   
  102.         public ActionResult OrdersByCustomer()  
  103.         {  
  104.             DashboardContext _context = new DashboardContext();  
  105.             var ordersByCustomer = (from o in _context.OrderSet  
  106.                                     group o by o.Customer.ID into g  
  107.                                     select new  
  108.                                     {  
  109.                                         Name = from c in _context.CustomerSet  
  110.                                                where c.ID == g.Key  
  111.                                                select c.CustomerName,  
  112.   
  113.                                         CountOrders = g.Count()  
  114.   
  115.                                     }).ToList();  
  116.   
  117.   
  118.             return Json(new { result = ordersByCustomer }, JsonRequestBehavior.AllowGet);  
  119.         }  
  120.   
  121.   
  122.         public List<ProductOrCustomerViewModel> GetProductOrCustomer(string type)  
  123.         {  
  124.             List<ProductOrCustomerViewModel> result = null;  
  125.   
  126.             using (DashboardContext _context = new DataAccess.DashboardContext())  
  127.             {  
  128.                 if (!string.IsNullOrEmpty(type))  
  129.                 {  
  130.                     if (type == "customers")  
  131.                     {  
  132.                         result = _context.CustomerSet.Select(c => new ProductOrCustomerViewModel  
  133.                         {  
  134.                             Name = c.CustomerName,  
  135.                             Image = c.CustomerImage,  
  136.                             TypeOrCountry = c.CustomerCountry,  
  137.                             Type = "Customers"  
  138.   
  139.                         }).ToList();  
  140.   
  141.                     }  
  142.                     else if (type == "products")  
  143.                     {  
  144.                         result = _context.ProductSet.Select(p => new ProductOrCustomerViewModel  
  145.                         {  
  146.                             Name = p.ProductName,  
  147.                             Image = p.ProductImage,  
  148.                             TypeOrCountry = p.ProductType,  
  149.                             Type = p.ProductType  
  150.   
  151.                         }).ToList();  
  152.   
  153.                     }  
  154.                 }  
  155.   
  156.                 return result;  
  157.             }  
  158.   
  159.         }  
  160.     }  
  161. }  

Now, we will explain all the actions which are defined within DashboardController.

Dashboard action is the main action that represents our dashboard with different KPIs (Key Performance Indicator).

Dashboard.cshtml

  1. @{  
  2.     ViewBag.Title = "Dashboard";  
  3. }  
  4. <div id="page-wrapper">  
  5.     <div class="row">  
  6.         <div class="col-lg-12">  
  7.             <h1 class="page-header">Dashboard</h1>  
  8.         </div>  
  9.         <!-- /.col-lg-12 -->  
  10.     </div>  
  11.     <!-- /.row -->  
  12.     <div class="row">  
  13.         <div class="col-lg-4 col-md-6">  
  14.             <div class="panel panel-primary">  
  15.                 <div class="panel-heading">  
  16.                     <div class="row">  
  17.                         <div class="col-xs-3">  
  18.                             <i class="fa fa-comments fa-5x"></i>  
  19.                         </div>  
  20.                         <div class="col-xs-9 text-right">  
  21.                             <div class="huge" id="CountCustomers">  
  22.                                 <span>  
  23.                                     @if (ViewBag.CountCustomers != null)  
  24.                                     {  
  25.                                         @ViewBag.CountCustomers;  
  26.                                     }  
  27.                                 </span>  
  28.   
  29.                             </div>  
  30.                             <div>Customers!</div>  
  31.                         </div>  
  32.                     </div>  
  33.                 </div>  
  34.                 <a href="#" class="viewDetails" data-type="customers">  
  35.                     <div class="panel-footer">  
  36.                         <span class="pull-left">View Details</span>  
  37.                         <span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>  
  38.                         <div class="clearfix"></div>  
  39.                     </div>  
  40.                 </a>  
  41.             </div>  
  42.         </div>  
  43.         <div class="col-lg-4 col-md-6">  
  44.             <div class="panel panel-green">  
  45.                 <div class="panel-heading">  
  46.                     <div class="row">  
  47.                         <div class="col-xs-3">  
  48.                             <i class="fa fa-tasks fa-5x"></i>  
  49.                         </div>  
  50.                         <div class="col-xs-9 text-right">  
  51.                             <div class="huge" id="CountOrders">  
  52.                                 <span>  
  53.                                     @if (ViewBag.CountOrders != null)  
  54.                                     {  
  55.                                         @ViewBag.CountOrders;  
  56.                                     }  
  57.                                 </span>  
  58.                              </div>  
  59.                             <div>Orders!</div>  
  60.                         </div>  
  61.                     </div>  
  62.                 </div>  
  63.                 <a href="#">  
  64.                     <div class="panel-footer">  
  65.                         <span class="pull-left">View Details</span>  
  66.                         <span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>  
  67.                         <div class="clearfix"></div>  
  68.                     </div>  
  69.                 </a>  
  70.             </div>  
  71.         </div>  
  72.         <div class="col-lg-4 col-md-6">  
  73.             <div class="panel panel-yellow">  
  74.                 <div class="panel-heading">  
  75.                     <div class="row">  
  76.                         <div class="col-xs-3">  
  77.                             <i class="fa fa-shopping-cart fa-5x"></i>  
  78.                         </div>  
  79.                         <div class="col-xs-9 text-right">  
  80.                             <div class="huge" id="CountProducts">  
  81.                                 <span>  
  82.                                     @if (ViewBag.CountProducts != null)  
  83.                                     {  
  84.                                         @ViewBag.CountProducts;  
  85.                                     }  
  86.                                 </span>  
  87.                             </div>  
  88.                             <div>Products!</div>  
  89.                         </div>  
  90.                     </div>  
  91.                 </div>  
  92.                 <a href="#" class="viewDetails" data-type="products">  
  93.                     <div class="panel-footer">  
  94.                         <span class="pull-left">View Details</span>  
  95.                         <span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>  
  96.                         <div class="clearfix"></div>  
  97.                     </div>  
  98.                 </a>  
  99.             </div>  
  100.         </div>  
  101.   
  102.     </div>  
  103.     <!-- /.row -->  
  104.     <div class="row">  
  105.         <div class="col-lg-8">  
  106.             <div class="panel panel-default">  
  107.                 <div class="panel-heading">  
  108.                     <i class="fa fa-bar-chart-o fa-fw"></i> ORDERS BY COUNTRY  
  109.   
  110.                 </div>  
  111.                 <!-- /.panel-heading -->  
  112.                 <div class="panel-body">  
  113.                     <div id="orderByCountry"></div>  
  114.                 </div>  
  115.                 <!-- /.panel-body -->  
  116.             </div>  
  117.             <!-- /.panel -->  
  118.             <div class="panel panel-default">  
  119.                 <div class="panel-heading">  
  120.                     <i class="fa fa-bar-chart-o fa-fw"></i> ORDERS BY CUSTOMER  
  121.                 </div>  
  122.                 <!-- /.panel-heading -->  
  123.                 <div class="panel-body">  
  124.                     <div class="row">  
  125.   
  126.                         <div class="col-lg-12">  
  127.                             <div id="ordersByCustomer"></div>  
  128.                         </div>  
  129.                         <!-- /.col-lg-8 (nested) -->  
  130.                     </div>  
  131.                     <!-- /.row -->  
  132.                 </div>  
  133.                 <!-- /.panel-body -->  
  134.             </div>  
  135.             <!-- /.panel -->  
  136.             <div class="panel panel-default">  
  137.                 <div class="panel-heading">  
  138.                     <i class="fa fa-clock-o fa-fw"></i> CUSTOMERS LIST  
  139.                 </div>  
  140.                 <!-- /.panel-heading -->  
  141.                 <div class="panel-body">  
  142.                     <table id="myDataTable" class="table table-bordered table-striped table-hover">  
  143.                         <thead>  
  144.                             <tr>  
  145.                                 <th>Customer Profil</th>  
  146.                                 <th>Customer ID</th>  
  147.                                 <th>Customer Name</th>  
  148.                                 <th>Customer Email</th>  
  149.                                 <th>Customer Phone</th>  
  150.                                 <th>Customer Country</th>  
  151.                             </tr>  
  152.                         </thead>  
  153.                     </table>  
  154.                 </div>  
  155.                 <!-- /.panel-body -->  
  156.             </div>  
  157.             <!-- /.panel -->  
  158.         </div>  
  159.         <!-- /.col-lg-8 -->  
  160.         <div class="col-lg-4">  
  161.             <div class="panel panel-default">  
  162.                 <div class="panel-heading">  
  163.                     <i class="fa fa-bell fa-fw"></i> TOP 5 CUSTOMERS  
  164.                 </div>  
  165.                 <!-- /.panel-heading -->  
  166.                 <div class="panel-body topCustomer">  
  167.                 </div>  
  168.                 <!-- /.panel-body -->  
  169.             </div>  
  170.             <!-- /.panel -->  
  171.             <div class="panel panel-default">  
  172.                 <div class="panel-heading">  
  173.                     <i class="fa fa-bar-chart-o fa-fw"></i> CUSTOMER BY COUNTRY  
  174.                 </div>  
  175.                 <div class="panel-body">  
  176.                     <div id="customerByCountry"></div>  
  177.                 </div>  
  178.                 <!-- /.panel-body -->  
  179.             </div>  
  180.             <!-- /.panel -->  
  181.   
  182.         </div>  
  183.         <!-- /.col-lg-4 -->  
  184.     </div>  
  185.     <!-- /.row -->  
  186. </div>  
  187. <!-- /#page-wrapper -->  
  188. <!-- MODAL -->  
  189. <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">  
  190.     <div class="modal-dialog" role="document">  
  191.         <div class="modal-content">  
  192.             <div class="modal-header">  
  193.                 <h4 class="modal-title" id="exampleModalLabel"> <span class="glyphicon glyphicon-search"></span> View Details </h4>  
  194.                 <button type="button" class="close" data-dismiss="modal" aria-label="Close">  
  195.                     <span aria-hidden="true">×</span>  
  196.                 </button>  
  197.             </div> <!-- MODEL HEADER-->  
  198.             <div class="modal-body">  
  199.   
  200.             </div> <!-- MODAL BODY-->  
  201.         </div>  
  202.     </div>  
  203. </div>  
  204. <!-- JS -->  
  205. @section Scripts{  
  206.     <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>  
  207.     <script type="text/javascript" src="https://www.google.com/jsapi"></script>   
  208.     <script type="text/javascript" src="https://www.google.com/uds/api/visualization/1.0/40ff64b1d9d6b3213524485974f36cc0/format+en,default+en,ui+en,corechart+en.I.js"></script>  
  209.    <script src="~/Scripts/dataTables.bootstrap.min.js"></script>  
  210.     <script type="text/javascript">  
  211.         //Global Variable  
  212.         google.load("visualization""1", { packages: ["corechart"] });  
  213.         $(document).ready(function () {  
  214.   
  215.   
  216.   
  217.             //View Details Button  
  218.             $(".viewDetails").click(function () {  
  219.                 $(".modal-body").html('');  
  220.                 $.ajax({  
  221.                     type: 'GET',  
  222.                     url: '@Url.Action("GetDetails", "Dashboard")',  
  223.                     data: { type: $(this).attr("data-type") },  
  224.                     success: function (response) {  
  225.                         $(".modal-body").html(response);  
  226.                         $("#exampleModal").modal('show');  
  227.                     },  
  228.                     error: function () {  
  229.                         alert("Something wrong");  
  230.                     }  
  231.                 });  
  232.             });  
  233.             //Panel Body  
  234.             $.ajax({  
  235.                 type: 'GET',  
  236.                 url: '@Url.Action("TopCustomers", "Dashboard")',  
  237.                 success: function (response) {  
  238.                     $(".topCustomer").html(response);  
  239.                 },  
  240.                 error: function () {  
  241.                     alert("Something Wrong");  
  242.                 }  
  243.             });  
  244.   
  245.              //Chart Orders By Country  
  246.             OrdersByCountry()  
  247.   
  248.             //Chart Customer By Country  
  249.             CustomersByCountry()  
  250.   
  251.             //Chart Orders By Customer  
  252.             OrdersByCustomer()  
  253.   
  254.             //Get All Customers   
  255.             CustomerList()  
  256.             //function  Orders By Country  
  257.             function OrdersByCountry() {  
  258.   
  259.                 $.ajax({  
  260.                     type: 'GET',  
  261.                     url: '@Url.Action("OrdersByCountry", "Dashboard")',  
  262.                     success: function (response) {  
  263.                         console.log(response);  
  264.   
  265.                         var data = new google.visualization.DataTable();  
  266.   
  267.                         data.addColumn('string''Country');  
  268.                         data.addColumn('number''CountOrders');  
  269.   
  270.                         for (var i = 0; i < response.result.length; i++) {  
  271.                             data.addRow([response.result[i].Country, response.result[i].CountOrders]);  
  272.                         }  
  273.   
  274.   
  275.                         var chart = new google.visualization.ColumnChart(document.getElementById('orderByCountry'));  
  276.   
  277.                         chart.draw(data,  
  278.                           {  
  279.                               title: "",  
  280.                               position: "top",  
  281.                               fontsize: "14px",  
  282.                               chartArea: { width: '100%' },  
  283.                           });  
  284.                     },  
  285.                     error: function () {  
  286.                         alert("Error loading data!");  
  287.                     }  
  288.                 });  
  289.   
  290.             }  
  291.   
  292.             function CustomersByCountry() {  
  293.   
  294.                 $.ajax({  
  295.                     type: 'GET',  
  296.                     url: '@Url.Action("CustomersByCountry", "Dashboard")',  
  297.                     success: function (response) {  
  298.   
  299.                         console.log(response);  
  300.   
  301.                         var data = new google.visualization.DataTable();  
  302.   
  303.                         data.addColumn('string''Country');  
  304.                         data.addColumn('number''CountCustomer');  
  305.   
  306.                         for (var i = 0; i < response.result.length; i++) {  
  307.                             data.addRow([response.result[i].Country, response.result[i].CountCustomer]);  
  308.                         }  
  309.   
  310.   
  311.                         var chart = new google.visualization.PieChart(document.getElementById('customerByCountry'));  
  312.   
  313.                         chart.draw(data,  
  314.                           {  
  315.                               title: "",  
  316.                               position: "top",  
  317.                               fontsize: "14px",  
  318.                               chartArea: { width: '100%' },  
  319.                           });  
  320.                     },  
  321.                     error: function () {  
  322.                         alert("Error loading data!");  
  323.                     }  
  324.                 });  
  325.   
  326.             }  
  327.             function OrdersByCustomer() {  
  328.                 $.ajax({  
  329.                     type: 'GET',  
  330.                     url: '@Url.Action("OrdersByCustomer", "Dashboard")',  
  331.                     success: function (response) {  
  332.                         console.log(response);  
  333.                         var data = new google.visualization.DataTable();  
  334.                         data.addColumn('string''Name');  
  335.                         data.addColumn('number''CountOrders');  
  336.                         for (var i = 0; i < response.result.length; i++) {  
  337.                             data.addRow([response.result[i].Name[0], response.result[i].CountOrders]);  
  338.                         }  
  339.                         var chart = new google.visualization.BarChart(document.getElementById('ordersByCustomer'));  
  340.   
  341.                         chart.draw(data,  
  342.                           {  
  343.                               title: "",  
  344.                               position: "top",  
  345.                               fontsize: "14px",  
  346.                               chartArea: { width: '100%' },  
  347.                           });  
  348.                     },  
  349.                     error: function () {  
  350.                         alert("Error loading data!");  
  351.                     }  
  352.                 });  
  353.   
  354.             }  
  355.             function CustomerList() {  
  356.                 //GET DATA FROM DATABASE TO FILL DATATABLE  
  357.                 var oTable = $(".panel #myDataTable").DataTable({  
  358.   
  359.                     "ajax": {  
  360.                         "url""/CustomerOrder/GetCustomers",  
  361.                         "type""GET",  
  362.                         "dataType""json"  
  363.                     },  
  364.   
  365.                     "columns": [  
  366.                         {  
  367.                             "data""CustomerImage""width""50px""render"function (data) {  
  368.                                 return '<img class="rounded img-thumbnail" style="width:60px; height:58px;" src="/Images/Customers/' + data + '"/>';  
  369.                             }  
  370.                         },  
  371.                         { "data""ID""autowidth"true },  
  372.                         { "data""CustomerName""autowidth"true },  
  373.                         { "data""CustomerEmail""autowidth"true },  
  374.                         { "data""CustomerPhone""autowidth"true },  
  375.                         { "data""CustomerCountry""autowidth"true }  
  376.                     ]  
  377.                 });  
  378.             }  
  379.         });  
  380.     </script>  
  381. }  

Here, GetDetails action is responsible to get all products or customers based on type parameter which takes as value customer or product type then we will loop the returned result within GetDetails partial view.

GetDetails.cshtml

Copy-past the following code snipped

  1. @model IEnumerable<ApplicationDashboardMVC.Models.ProductOrCustomerViewModel>  
  2. @using ApplicationDashboardMVC.Helpers;  
  3.   
  4. <table class="table table-hover">  
  5.     
  6.     @foreach (var md in Model)  
  7.     {  
  8.         <tr>  
  9.             <td> @Html.ProductImage(@md.Type, @md.Image, "60px""58px") </td>  
  10.             <td>@md.Name </td>  
  11.             <td>@md.TypeOrCountry </td>  
  12.         </tr>  
  13.     }  
  14.   
  15. </table>  
  16.   
  17. <script type="text/javascript">  
  18.   
  19.     $('img').addClass('rounded img-thumbnail');  
  20.   
  21. </script>  

TopCustomers action is used to get top 5 customers who made more orders, then we will use TopCustomers partial view to display result.

TopCustomers.cshtml

  1. @model IEnumerable<ApplicationDashboardMVC.Models.TopCustomerViewModel>  
  2.   
  3. <div class="list-group">  
  4.   
  5.     @foreach (var customer in Model)  
  6.     {  
  7.         <a href="#" class="list-group-item">  
  8.             <div style="display: inline-block;width: 60px;">  
  9.                 <img class="rounded img-thumbnail" src="@string.Format("/Images/Customers/{0}", customer.CustomerImage)" alt="" style="width:50px; height:60px;" />  
  10.             </div>  
  11.   
  12.             @customer.CustomerName  
  13.             <span class="label label-info"> @string.Format("{0} : {1}""Count Orders", customer.CountOrder) </span>  
  14.             <span class="label label-success" style="margin-left: 10px;"> @string.Format("{0} : {1}""From", customer.CustomerCountry) </span>  
  15.   
  16.         </a>  
  17.     }  
  18.   
  19. </div>  

Next, OrdersByCountry action will help us to return as result the number of orders by country in JSON format.

Now, let’s switch to CustomersByCountry which has the role to return the number of customers by country in JSON format.

Finally, we have OrdersbyCustomer action which is used to return the number of orders by customer.

Note

Do not forget to add the following view models

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace ApplicationDashboardMVC.Models  
  7. {  
  8.     public class ProductsViewModel  
  9.     {  
  10.         public int ProductID { get; set; }  
  11.         public string ProductName { get; set; }  
  12.         public decimal UnitPriceProduct { get; set; }  
  13.         public int UnitsInStock { get; set; }  
  14.         public string ProductImage { get; set; }  
  15.         public string ProductType { get; set; }  
  16.         public int QteSelected { get; set; }  
  17.   
  18.     }  
  19.   
  20.     public class ProductOrCustomerViewModel  
  21.     {  
  22.         public string Name { get; set; }  
  23.         public string Image { get; set; }  
  24.         public string TypeOrCountry { get; set; }  
  25.         public string Type { get; set; }  
  26.     }  
  27.   
  28.     public class TopCustomerViewModel  
  29.     {  
  30.         public string CustomerName { get; set; }  
  31.         public string CustomerImage { get; set; }  
  32.         public string CustomerCountry { get; set; }  
  33.         public int CountOrder { get; set; }  
  34.     }  
  35. }  

That’s all, Please send your feedback and queries in comments box.