How To Implement Google Column Chart Dynamically Using Entity Framework And MVC 5

Introduction

In this article, I will demonstrate how to implement Google Column Chart dynamically using Entity Framework in MVC5. I will use jQuery AJAX to retrieve the data from the database and display it in Google Column Chart. The chart will animate columns with their respective data display in it. 

Step 1

Open SQL Server 2014 and create a database table to insert and retrieve the data.

  1. CREATE TABLE [dbo].[CompanyHiring](  
  2.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Year] [intNULL,  
  4.     [Accounts] [intNULL,  
  5.     [HR] [intNULL,  
  6.     [IT] [intNULL,  
  7.  CONSTRAINT [PK_CompanyHiring] PRIMARY KEY CLUSTERED   
  8. (  
  9.     [ID] ASC  
  10. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  11. ON [PRIMARY]  
  12.   
  13. GO  

Screenshot for a database table

ASP.NET

Step 2

Open Visual Studio 2015, click on New Project and create an empty web application project.

Screenshot 1 for creating a new project

ASP.NET

After clicking on New Project, one window will appear. Select Web from the left panel, choose ASP.NET Web Application to give a meaningful name to your project. Then, click on OK as shown in the below screenshot.

Screenshot 2 for creating a new project 

ASP.NET

After clicking on OK, one more window will appear. Choose Empty, check on MVC checkbox, and click on OK.

Screenshot for creating a new project-3

ASP.NET

After clicking on OK, the project will be created with the name of MvcGoogleColumnChart_Demo.

Step 3

Add Entity Framework, right click on Models folder, select Add. Then, select New Item, then click on it.

Screenshot 1 for adding Entity Framework

ASP.NET

After clicking on the new item, you will get a window from there. Select Data from the left panel and choose ADO.NET Entity Data Model, give it a name as DBModels (This name is not mandatory; you can give any name), and click on Add.

Screenshot 2 for adding Entity Framework

ASP.NET

After you click on Add, a wizard will open. Choose EF Designer from the database and click Next.

Screenshot 3 for adding Entity Framework

ASP.NET

On the next window, choose New Connection.

Screenshot 4 for adding Entity Framework

ASP.NET

Another window will appear. Add your server name. If it is local, then enter dot (.). Choose your database and click on OK.

Screenshot 5 for adding Entity Framework

ASP.NET

The connection will get added. If you wish to save it, connect as you want. You can change the name of your connection below. It will save the connection in web config, then click on Next.

Screenshot 6 for adding Entity Framework

ASP.NET

After clicking on NEXT, another window will appear. Choose database table name as shown in the below screenshot. Then, click on Finish. Entity Framework will be added and respective class gets generated under Models folder.

Screenshot 7 for adding Entity Framework

ASP.NET

Screenshot 8 for adding Entity Framework

ASP.NET

The following class will be added.

  1. namespace MvcGoogleColumnChart_Demo.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.     using System.ComponentModel.DataAnnotations;  
  6.       
  7.     public partial class CompanyHiring  
  8.     {  
  9.         public int ID { get; set; }  
  10.         [Required(ErrorMessage ="Please enter year hired")]  
  11.         public Nullable<int> Year { get; set; }  
  12.         [Required(ErrorMessage = "Enter number of employees hired in Account department")]  
  13.         public Nullable<int> Accounts { get; set; }  
  14.         [Required(ErrorMessage = "Enter number of employees hired in HR department")]  
  15.         public Nullable<int> HR { get; set; }  
  16.         [Required(ErrorMessage = "Enter number of employees hired in IT department")]  
  17.         public Nullable<int> IT { get; set; }  
  18.     }  
  19. }  

Step 4

Right click on Controllers folder, select Add, then choose Controller.

ASP.NET

After clicking on the Controller, a window will appear. Choose MVC5 Controller-Empty and click on Add.

ASP.NET

After clicking on Add, another window will appear with DefaultController. Change the name to HomeController, then click on Add. HomeController will be added to Controllers folder. Remember, don’t change Controller. Instead of Default just change Home.

ASP.NET

Add the following namespace in Controller.

using MvcGoogleColumnChart_Demo. Models;

Complete Controller code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcGoogleColumnChart_Demo.Models;  
  7.   
  8. namespace MvcGoogleColumnChart_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         // GET: Home  
  13.         public ActionResult Index()  
  14.         {  
  15.             return View();  
  16.         }  
  17.         public ActionResult Column()  
  18.         {  
  19.             return View();  
  20.         }  
  21.         [HttpPost]  
  22.         public ActionResult Column(CompanyHiring company)  
  23.         {  
  24.             using (DBModel db = new DBModel())  
  25.             {  
  26.                 db.CompanyHirings.Add(company);  
  27.                 db.SaveChanges();  
  28.             }  
  29.             return View();  
  30.         }  
  31.         public JsonResult GetHireData()  
  32.         {  
  33.             List<CompanyHiring> CompanyHireData = new List<CompanyHiring>();  
  34.             using (DBModel db=new DBModel())  
  35.             {  
  36.                 CompanyHireData = db.CompanyHirings.OrderBy(a => a.Year).ToList();  
  37.             }  
  38.             var chartData = new object[CompanyHireData.Count + 1];  
  39.             chartData[0] = new object[]{  
  40.                     "Year",  
  41.                     "Account",  
  42.                     "HR",  
  43.                     "IT"  
  44.                 };  
  45.             int j = 0;  
  46.             foreach (var i in CompanyHireData)  
  47.             {  
  48.                 j++;  
  49.                 chartData[j] = new object[] { i.Year, i.Accounts, i.HR, i.IT};  
  50.             }  
  51.   
  52.             return new JsonResult { Data = chartData, JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
  53.         }  
  54.     }  
  55. }  

Step 5

Right-click on Column action method in Controller. An "Add View" window will appear with default Column name unchecked (use a Layout page), click on Add. The View will be added in Views folder under Home folder with name Column.

Screenshot for adding View

ASP.NET

Step 6

Click on Tools, select NuGet Package Manager, then choose Manage NuGet Packages for Solution click on it.

Screenshot for NuGet Package

ASP.NET

After that, a window will appear. Choose Browse type as bootstrap and install the package in the project.

ASP.NET

Similarly, type jQuery and install the latest version of jQuery package in the project and jQuery validation file from NuGet, then close NuGet Solution.

ASP.NET

Keep the required bootstrap and jQuery file and delete the remaining file if not using. Or you can download and add in the project.

Step 7

Add required script and style in head section of the View.

  1. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  2. <script type="text/javascript" src="https://www.google.com/jsapi"></script>  
  3. <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  4. <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  5. <script src="~/scripts/bootstrap.min.js"></script>      
  6. <script src="~/scripts/ColumnCart.js"></script>  
  7. <script src="~/scripts/jquery.validate.min.js"></script>  
  8. <script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>  

Step 8

Right-click on Scripts folder, select Add, and choose JavaScript file. Give it a name as ColumnCart.js. Write the script to get data from the database.

  1. $(document).ready(function () {  
  2.     //Load Data Here  
  3.     var chartData = null;  
  4.     $.ajax({  
  5.         url: '/Home/GetHireData',  
  6.         type: 'GET',  
  7.         dataType: 'json',  
  8.         data: '',  
  9.         success: function (d) {  
  10.             chartData = d;  
  11.         },  
  12.         error: function () {  
  13.             alert('Error!');  
  14.         }  
  15.     }).done(function () {  
  16.         drawChart(chartData);  
  17.     });  
  18. });  
  19. function drawChart(d) {  
  20.     var chartData = d;  
  21.     var data = null;  
  22.     data = google.visualization.arrayToDataTable(chartData);  
  23.   
  24.     var view = new google.visualization.DataView(data);  
  25.     view.setColumns([0, {  
  26.         type: 'number',  
  27.         label: data.getColumnLabel(0),  
  28.         calc: function () { return 0; }  
  29.     }, {  
  30.         type: 'number',  
  31.         label: data.getColumnLabel(1),  
  32.         calc: function () { return 0; }  
  33.     }, {  
  34.         type: 'number',  
  35.         label: data.getColumnLabel(2),  
  36.         calc: function () { return 0; }  
  37.     }, {  
  38.         type: 'number',  
  39.         label: data.getColumnLabel(3),  
  40.         calc: function () { return 0; }  
  41.     }]);  
  42.     var chart = new google.visualization.ColumnChart(document.getElementById('visualization'));  
  43.     var options = {  
  44.         title: 'Company Hiring Report',  
  45.         legend: 'bottom',  
  46.         hAxis: {  
  47.             title: 'Year',  
  48.             format: '#'  
  49.         },  
  50.         vAxis: {  
  51.             minValue: 0,  
  52.             maxValue: 1000,  
  53.             title: 'Company Hire Employee'  
  54.         },  
  55.         chartArea: {  
  56.             left: 100, top: 50, width: '70%', height: '50%'  
  57.         },  
  58.         animation: {  
  59.             duration: 1000  
  60.         }  
  61.     };  
  62.     var runFirstTime = google.visualization.events.addListener(chart, 'ready'function () {  
  63.         google.visualization.events.removeListener(runFirstTime);  
  64.         chart.draw(data, options);  
  65.     });  
  66.   
  67.     chart.draw(view, options);  
  68. }  
  69. google.load('visualization''1', { packages: ['corechart'] });  

Step 9

Design the View with HTML, cshtml, and bootstrap 4 classes.

  1. <body>  
  2.     @using (Html.BeginForm("Column""Home", FormMethod.Post))  
  3.     {  
  4.         <div class="container py-4">  
  5.             <h2 class="text-uppercase text-center">Column Chart With Animation using MVC5</h2>  
  6.             <div class="card">  
  7.                 <div class="card-header bg-danger">  
  8.                     <h6 class="card-title text-uppercase text-white">Company hiring Report</h6>  
  9.                 </div>  
  10.                 <div class="card-body">  
  11.                     <button type="button" style="margin-bottom:10px;" class="btn btn-primary rounded-0" data-toggle="modal" data-target="#CompanyReport"><i class="fa fa-plus-circle"></i> Add New Report</button>  
  12.                     <div class="modal fade" id="CompanyReport">  
  13.                         <div class="modal-dialog modal-lg">  
  14.                             <div class="modal-content">  
  15.                                 <div class="modal-header">  
  16.                                     <h6 class="modal-title">New Hiring Report</h6>  
  17.                                     <button type="button" class="close" data-dismiss="modal">×</button>  
  18.                                 </div>  
  19.                                 <div class="modal-body">  
  20.                                     <div class="row">  
  21.                                         <div class="col-sm-6 col-md-6 col-xs-12">  
  22.                                             <div class="form-group">  
  23.                                                 <label>Report Year</label>  
  24.                                                 @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control" } })  
  25.                                                 @Html.ValidationMessageFor(model => model.Year, ""new { @class = "text-danger" })  
  26.                                             </div>  
  27.                                         </div>  
  28.                                         <div class="col-sm-6 col-md-6 col-xs-12">  
  29.                                             <div class="form-group">  
  30.                                                 <label>Account</label>  
  31.                                                 @Html.EditorFor(model => model.Accounts, new { htmlAttributes = new { @class = "form-control" } })  
  32.                                                 @Html.ValidationMessageFor(model => model.Accounts, ""new { @class = "text-danger" })  
  33.                                             </div>  
  34.                                         </div>  
  35.                                     </div>  
  36.                                     <div class="row">  
  37.                                         <div class="col-sm-6 col-md-6 col-xs-12">  
  38.                                             <div class="form-group">  
  39.                                                 <label>HR</label>  
  40.                                                 @Html.EditorFor(model => model.HR, new { htmlAttributes = new { @class = "form-control" } })  
  41.                                                 @Html.ValidationMessageFor(model => model.HR, ""new { @class = "text-danger" })  
  42.                                             </div>  
  43.                                         </div>  
  44.                                         <div class="col-sm-6 col-md-6 col-xs-12">  
  45.                                             <div class="form-group">  
  46.                                                 <label>IT</label>  
  47.                                                 @Html.EditorFor(model => model.IT, new { htmlAttributes = new { @class = "form-control" } })  
  48.                                                 @Html.ValidationMessageFor(model => model.IT, ""new { @class = "text-danger" })  
  49.                                             </div>  
  50.                                         </div>  
  51.                                     </div>  
  52.                                 </div>  
  53.                                 <div class="modal-footer">  
  54.                                     <button type="button" class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>  
  55.                                     <button class="btn btn-primary rounded-0">Submit Report</button>  
  56.                                 </div>  
  57.                             </div>  
  58.                         </div>  
  59.                     </div>  
  60.                     <div id="visualization" style="width:100%; height:400px">  
  61.                     </div>  
  62.                 </div>  
  63.             </div>  
  64.         </div>  
  65.     }  
  66. </body>  

Complete View code

  1. @model MvcGoogleColumnChart_Demo.Models.CompanyHiring  
  2. @{  
  3.     Layout = null;  
  4. }  
  5.   
  6. <!DOCTYPE html>  
  7.   
  8. <html>  
  9. <head>  
  10.     <meta name="viewport" content="width=device-width" />  
  11.     <title>Column</title>  
  12.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  13.     <script type="text/javascript" src="https://www.google.com/jsapi"></script>  
  14.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  15.     <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  16.     <script src="~/scripts/bootstrap.min.js"></script>      
  17.     <script src="~/scripts/ColumnCart.js"></script>  
  18.     <script src="~/scripts/jquery.validate.min.js"></script>  
  19.     <script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>  
  20. </head>  
  21. <body>  
  22.     @using (Html.BeginForm("Column""Home", FormMethod.Post))  
  23.     {  
  24.         <div class="container py-4">  
  25.             <h2 class="text-uppercase text-center">Column Chart With Animation using MVC5</h2>  
  26.             <div class="card">  
  27.                 <div class="card-header bg-danger">  
  28.                     <h6 class="card-title text-uppercase text-white">Company hiring Report</h6>  
  29.                 </div>  
  30.                 <div class="card-body">  
  31.                     <button type="button" style="margin-bottom:10px;" class="btn btn-primary rounded-0" data-toggle="modal" data-target="#CompanyReport"><i class="fa fa-plus-circle"></i> Add New Report</button>  
  32.                     <div class="modal fade" id="CompanyReport">  
  33.                         <div class="modal-dialog modal-lg">  
  34.                             <div class="modal-content">  
  35.                                 <div class="modal-header">  
  36.                                     <h6 class="modal-title">Company Hiring New Report</h6>  
  37.                                     <button type="button" class="close" data-dismiss="modal">×</button>  
  38.                                 </div>  
  39.                                 <div class="modal-body">  
  40.                                     <div class="row">  
  41.                                         <div class="col-sm-6 col-md-6 col-xs-12">  
  42.                                             <div class="form-group">  
  43.                                                 <label>Year</label>  
  44.                                                 @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control" } })  
  45.                                                 @Html.ValidationMessageFor(model => model.Year, ""new { @class = "text-danger" })  
  46.                                             </div>  
  47.                                         </div>  
  48.                                         <div class="col-sm-6 col-md-6 col-xs-12">  
  49.                                             <div class="form-group">  
  50.                                                 <label>Account</label>  
  51.                                                 @Html.EditorFor(model => model.Accounts, new { htmlAttributes = new { @class = "form-control" } })  
  52.                                                 @Html.ValidationMessageFor(model => model.Accounts, ""new { @class = "text-danger" })  
  53.                                             </div>  
  54.                                         </div>  
  55.                                     </div>  
  56.                                     <div class="row">  
  57.                                         <div class="col-sm-6 col-md-6 col-xs-12">  
  58.                                             <div class="form-group">  
  59.                                                 <label>HR</label>  
  60.                                                 @Html.EditorFor(model => model.HR, new { htmlAttributes = new { @class = "form-control" } })  
  61.                                                 @Html.ValidationMessageFor(model => model.HR, ""new { @class = "text-danger" })  
  62.                                             </div>  
  63.                                         </div>  
  64.                                         <div class="col-sm-6 col-md-6 col-xs-12">  
  65.                                             <div class="form-group">  
  66.                                                 <label>IT</label>  
  67.                                                 @Html.EditorFor(model => model.IT, new { htmlAttributes = new { @class = "form-control" } })  
  68.                                                 @Html.ValidationMessageFor(model => model.IT, ""new { @class = "text-danger" })  
  69.                                             </div>  
  70.                                         </div>  
  71.                                     </div>  
  72.                                 </div>  
  73.                                 <div class="modal-footer">  
  74.                                     <button type="button" class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>  
  75.                                     <button class="btn btn-primary rounded-0">Submit Report</button>  
  76.                                 </div>  
  77.                             </div>  
  78.                         </div>  
  79.                     </div>  
  80.                     <div id="visualization" style="width:100%; height:400px">  
  81.                     </div>  
  82.                 </div>  
  83.             </div>  
  84.         </div>  
  85.     }  
  86. </body>  
  87. </html>  

Step 10

Run Project ctrl+F5.

Screenshot 1

ASP.NET

Screenshot 2

ASP.NET

 

Conclusion

In this article.I have explained how we can dynamically implement Google Column Chart using Entity Framework and MVC5. We can add year of hiring,number of employee hired in account,hr and IT department clicking on Add New Report  button.I hope it will be useful in your upcoming projects.


Similar Articles