How To Implement Google Line Chart Dynamically Using Entity Framework In ASP.NET

Introduction

In this article, I will demonstrate how to implement Google Line Chart dynamically using Entity Framework in ASP.NET. I will use jQuery AJAX to retrieve the data from the database and display in Google Line Chart. The chart will display the respective data on its point line with an animation.

Step 1 Open SQL server 2014 and create a database table to insert the data and retrieve data.

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

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

Screenshot for creating new project 1

 

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

Screenshot for creating new project 2

 

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

Screenshot for creating new project 3

 

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

Screenshot for NuGet Package

 

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

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

 Keep the useful file in Content and scripts folder as shown below.

Step 4Add Entity Framework, right click on Models folder, select Add >> New Item and click on it.

Screenshot for adding entity framework 1

 

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

Screenshot for adding entity framework 2

 

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

Screenshot for adding entity framework 3

After clicking on Next, a window will appear. Choose New Connection.

Screenshot for adding entity framework 4

 

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

Screenshot for adding entity framework 5

 

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

Screenshot for adding entity framework 6

 

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 with the respective class which gets generated under Models folder.

Screenshot for adding entity framework 7

Screenshot for adding entity framework 8

Following class will be added.

  1. namespace GoogleLineChart_Demo.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.       
  6.     public partial class CompanyHiringReport  
  7.     {  
  8.         public int ID { get; set; }  
  9.         public Nullable<int> Year { get; set; }  
  10.         public Nullable<int> Account { get; set; }  
  11.         public Nullable<int> HR { get; set; }  
  12.         public Nullable<int> IT { get; set; }  
  13.         public Nullable<int> Sales { get; set; }  
  14.         public Nullable<int> Marketing { get; set; }  
  15.     }  
  16. }  

Step 5 Right click on the project, select Add, choose Web Form and click on it.

 

After clicking on the web form, one window will appear. Give it a meaningful name and click on OK.

Step 6 Right click on Scripts folder, select Add, choose JavaScript File, then click on it.

After clicking on the JavaScript file a window will appear. Give it the name LineChart, then click on OK.

Add the following jQuery and JavaScript code to retrieve data from the database and display it in the chart.

  1. var chartData; // globar variable for hold chart data  
  2. google.load("visualization""1", { packages: ["corechart"] });  
  3. // Here We will fill chartData  
  4. $(document).ready(function () {  
  5.     $.ajax({  
  6.         url: "GoogleLineChart.aspx/GetChartData",  
  7.         data: "",  
  8.         dataType: "json",  
  9.         type: "POST",  
  10.         contentType: "application/json; chartset=utf-8",  
  11.         success: function (data) {  
  12.             chartData = data.d;  
  13.         },  
  14.         error: function () {  
  15.             alert("Error loading data! Please try again.");  
  16.         }  
  17.     }).done(function () {  
  18.         // after complete loading data  
  19.         google.setOnLoadCallback(drawChart);  
  20.         drawChart();  
  21.     });  
  22. });  
  23. function drawChart() {  
  24.     var data = google.visualization.arrayToDataTable(chartData);  
  25.     var options = {  
  26.         title: "Company Hiring Report",  
  27.         pointSize: 5  
  28.     };  
  29.     var lineChart = new google.visualization.LineChart(document.getElementById(‘chart_div’));  
  30.     lineChart.draw(data, options);  
  31. }  

Step 7 Add the following scripts and styles in the head section of the web form.

  1. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  2.  “text/javascript” src=“https://www.google.com/jsapi”>  
  3.  <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  4.  “scripts/jquery-3.3.1.min.js”>  
  5.  “scripts/bootstrap.min.js”>  
  6.  “scripts/LineChart.js”>  

Step 8 Design the web form using textbox control, button control, and GridView control and Bootstrap 4 class to look good.

  1. <body>  
  2.     <form id="form1" runat="server">  
  3.        
    class=“container py-4”>  
  4.            
    class=“text-center text-uppercase”>How to Implement Google Line Chart Dynamically Using Entity Framework in Asp.Net

                

  5.            
    class=“card”>  
  6.                
    class=“card-header bg-primary”>  
  7.                    
    class=” text-upparcase text-white”>Company Hiring Report

      

  8.                 

  

  •                
    class=“card-body”>  
  •                       
  •                    
    class=“modal fade” id=“CompantReport”>  
  •                        
    class=“modal-dialog modal-lg”>  
  •                            
    class=“modal-content”>  
  •                                
    class=“modal-header”>  
  •                                    

    class=“modal-title”>New Hiring Report

      

  •                                       
  •                                 
  •   

  •                                
    class=“modal-body”>  
  •                                    
    class=“row”>  
  •                                        
    class=“col-md-4”>  
  •                                            
    class=“form-group”>  
  •                                                   
  •                                                 “txtYear” CssClass=“form-control” runat=“server”>  
  •                                                 “rfvYear” ControlToValidate=“txtYear” CssClass=“text-danger” runat=“server” ErrorMessage=“Please enter year”>  
  •                                             
  •   

  •                                         </div>  
  •                                        
    class=“col-md-4”>  
  •                                            
    class=“form-group”>  
  •                                                   
  •                                                 “txtAccountDepartment” CssClass=“form-control” runat=“server”>  
  •                                                 “rfvAccount” ControlToValidate=“txtYear” CssClass=“text-danger” runat=“server” ErrorMessage=“Please enter number employee hired”>  
  •                                             
  •   

  •                                         </div>  
  •                                        
    class=“col-md-4”>  
  •                                            
    class=“form-group”>  
  •                                                   
  •                                                 “txtHRDepartment” CssClass=“form-control” runat=“server”>  
  •                                                 “rfvHR” ControlToValidate=“txtHRDepartment” CssClass=“text-danger” runat=“server” ErrorMessage=“Please enter number employee hired”>  
  •                                             
  •   

  •                                         </div>  
  •                                     </div>  
  •                                    
    class=“row”>  
  •                                        
    class=“col-md-4”>  
  •                                            
    class=“form-group”>  
  •                                                 
  •                                                 “txtITDepartment” CssClass=“form-control” runat=“server”>  
  •                                                 “rfvIT” ControlToValidate=“txtITDepartment” CssClass=“text-danger” runat=“server” ErrorMessage=“Please enter number employee hired”>  
  •                                             
  •   

  •                                         </div>  
  •                                        
    class=“col-md-4”>  
  •                                            
    class=“form-group”>  
  •                                                   
  •                                                 “txtSalesDepartment” CssClass=“form-control” runat=“server”>  
  •                                                 “rfvSales” ControlToValidate=“txtSalesDepartment” CssClass=“text-danger” runat=“server” ErrorMessage=“Please enter number employee hired”>  
  •                                             
  •   

  •                                         </div>  
  •                                        
    class=“col-md-4”>  
  •                                            
    class=“form-group”>  
  •                                                   
  •                                                 “txtMarketingDepartment” CssClass=“form-control” runat=“server”>  
  •                                                 “rfvMarketing” ControlToValidate=“txtMarketingDepartment” CssClass=“text-danger” runat=“server” ErrorMessage=“Please enter number employee hired”>  
  •                                             
  •   

  •                                         </div>  
  •                                     </div>  
  •                                 </div>  
  •                                
    class=“modal-footer”>  
  •                                     “btnSubmit” CssClass=“btn btn-primary rounded-0” runat=“server” Text=“Submit” OnClick=“btnSubmit_Click” />  
  •                                       
  •                                 
  •   

  •                             </div>  
  •                         </div>  
  •                     </div>  
  •                     <asp:GridView ID="CompanyGridView" AutoGenerateColumns="false" runat="server" CssClass="table table-bordered table-striped">  
  •                         <Columns>  
  •                             <asp:BoundField HeaderText="ID" DataField="ID" />  
  •                             <asp:BoundField HeaderText="Year" DataField="Year" />  
  •                             <asp:BoundField HeaderText="Account Department" DataField="Account" />  
  •                             <asp:BoundField HeaderText="HR Department" DataField="HR" />  
  •                             <asp:BoundField HeaderText="IT Department" DataField="IT" />  
  •                             <asp:BoundField HeaderText="Sales Department" DataField="Sales" />  
  •                             <asp:BoundField HeaderText="Marketing Department" DataField="Marketing" />  
  •                         </Columns>  
  •                     </asp:GridView>  
  •                 </div>  
  •             </div>   
  •             
    “chart_div” style=“width: 100%; height: 400px”>  
  •             

                 

  •         </div>  
  •     </form>  
  • </body>  
  • Step 9 Double click on the submit button and write the following C# code.

    Add the following namespace.

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web.Script.Services;  
    5. using System.Web.Services;  
    6. using System.Web.UI.WebControls;  
    7. using GoogleLineChart_Demo.Models; 

    Complete C# code of web form

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web.Script.Services;  
    5. using System.Web.Services;  
    6. using System.Web.UI.WebControls;  
    7. using GoogleLineChart_Demo.Models;  
    8.   
    9. namespace GoogleLineChart_Demo  
    10. {  
    11.     public partial class GooglelineChart : System.Web.UI.Page  
    12.     {  
    13.         protected void Page_Load(object sender, EventArgs e)  
    14.         {  
    15.             if (!IsPostBack)  
    16.             {  
    17.                 BindGridView();  
    18.                 ClearTextBox();  
    19.             }  
    20.         }  
    21.   
    22.         private void ClearTextBox()  
    23.         {  
    24.             txtYear.Text = string.Empty;  
    25.             txtAccountDepartment.Text = string.Empty;  
    26.             txtHRDepartment.Text = string.Empty;  
    27.             txtITDepartment.Text = string.Empty;  
    28.             txtSalesDepartment.Text = string.Empty;  
    29.             txtMarketingDepartment.Text = string.Empty;  
    30.         }  
    31.   
    32.         private void BindGridView()  
    33.         {  
    34.             using (DBModel db = new DBModel())  
    35.             {  
    36.                 CompanyGridView.DataSource = (from r in db.CompanyHiringReports select r).ToList();  
    37.                 CompanyGridView.DataBind();  
    38.             }  
    39.         }  
    40.   
    41.         [WebMethod]  
    42.         [ScriptMethod(ResponseFormat = ResponseFormat.Json)]  
    43.         public static object[] GetChartData()  
    44.         {  
    45.             List<CompanyHiringReport> data = new List<CompanyHiringReport>();  
    46.             using (DBModel db = new DBModel())  
    47.             {  
    48.                 data = db.CompanyHiringReports.ToList();  
    49.             }  
    50.             var chartData = new object[data.Count + 1];  
    51.             chartData[0] = new object[]{  
    52.                 "Year",  
    53.                 "Accounts",  
    54.                 "HR",  
    55.                 "IT",  
    56.                 "Sales",  
    57.                 "Marketing"  
    58.             };  
    59.             int j = 0;  
    60.             foreach (var i in data)  
    61.             {  
    62.                 j++;  
    63.                 chartData[j] = new object[] { i.Year.ToString(), i.Account, i.HR, i.IT,i.Sales,i.Marketing };  
    64.             }  
    65.             return chartData;  
    66.         }  
    67.   
    68.         protected void btnSubmit_Click(object sender, EventArgs e)  
    69.         {  
    70.             using (DBModel db = new DBModel())  
    71.             {  
    72.                 CompanyHiringReport company = new CompanyHiringReport();  
    73.                 company.Year = Convert.ToInt32(txtYear.Text);  
    74.                 company.Account = Convert.ToInt32(txtAccountDepartment.Text);  
    75.                 company.HR = Convert.ToInt32(txtHRDepartment.Text);  
    76.                 company.IT = Convert.ToInt32(txtITDepartment.Text);  
    77.                 company.Sales = Convert.ToInt32(txtSalesDepartment.Text);  
    78.                 company.Marketing = Convert.ToInt32(txtMarketingDepartment.Text);  
    79.   
    80.                 db.CompanyHiringReports.Add(company);  
    81.                 db.SaveChanges();  
    82.                 ClearTextBox();  
    83.             }  
    84.             this.BindGridView();  
    85.         }  
    86.     }  
    87. }  

    Step 9 Right click on web config file and add the following code to avoid validation related errors.

    1. <appSettings>  
    2.   <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />  
    3. </appSettings>  

    Step 10 Run project by pressing ctrl+F5.

    Screenshot 1

    Screenshot 2

     

    Conclusion

    In this article, I have explained how to implement Google Line Chart dynamically using Entity Framework in ASP.NET. We can add yearly reports and department names by clicking on Add New Report button. We have understood it step by step. I hope it will be useful in your upcoming projects.

    Bunu paylaş:

    Bir cevap yazın

    E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    TOP