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.
- CREATE TABLE [dbo].[CompanyHiringReport](
- [ID] [int] IDENTITY(1,1) NOT NULL,
- [Year] [int] NULL,
- [Account] [int] NULL,
- [HR] [int] NULL,
- [IT] [int] NULL,
- [Sales] [int] NULL,
- [Marketing] [int] NULL,
- CONSTRAINT [PK_CompanyHiringReport] PRIMARY KEY CLUSTERED
- (
- [ID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
Step 2
Open 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 3
Click 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 4
Add 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.
- namespace GoogleLineChart_Demo.Models
- {
- using System;
- using System.Collections.Generic;
-
- public partial class CompanyHiringReport
- {
- public int ID { get; set; }
- public Nullable<int> Year { get; set; }
- public Nullable<int> Account { get; set; }
- public Nullable<int> HR { get; set; }
- public Nullable<int> IT { get; set; }
- public Nullable<int> Sales { get; set; }
- public Nullable<int> Marketing { get; set; }
- }
- }
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.
- var chartData;
- google.load("visualization", "1", { packages: ["corechart"] });
-
- $(document).ready(function () {
- $.ajax({
- url: "GoogleLineChart.aspx/GetChartData",
- data: "",
- dataType: "json",
- type: "POST",
- contentType: "application/json; chartset=utf-8",
- success: function (data) {
- chartData = data.d;
- },
- error: function () {
- alert("Error loading data! Please try again.");
- }
- }).done(function () {
-
- google.setOnLoadCallback(drawChart);
- drawChart();
- });
- });
- function drawChart() {
- var data = google.visualization.arrayToDataTable(chartData);
- var options = {
- title: "Company Hiring Report",
- pointSize: 5
- };
- var lineChart = new google.visualization.LineChart(document.getElementById('chart_div'));
- lineChart.draw(data, options);
- }
Step 7
Add the following scripts and styles in the head section of the web form.
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
- <script type="text/javascript" src="https://www.google.com/jsapi"></script>
- <link href="Content/bootstrap.min.css" rel="stylesheet" />
- <script src="scripts/jquery-3.3.1.min.js"></script>
- <script src="scripts/bootstrap.min.js"></script>
- <script src="scripts/LineChart.js"></script>
Step 8
Design the web form using textbox control, button control, and GridView control and Bootstrap 4 class to look good.
- <body>
- <form id="form1" runat="server">
- <div class="container py-4">
- <h5 class="text-center text-uppercase">How to Implement Google Line Chart Dynamically Using Entity Framework in Asp.Net</h5>
- <div class="card">
- <div class="card-header bg-primary">
- <h6 class=" text-upparcase text-white">Company Hiring Report</h6>
- </div>
- <div class="card-body">
- <button style="margin-bottom:10px;" class="btn btn-primary rounded-0" type="button" data-target="#CompantReport" data-toggle="modal"><i class="fa fa-plus-circle"></i>Add New Report</button>
- <div class="modal fade" id="CompantReport">
- <div class="modal-dialog modal-lg">
- <div class="modal-content">
- <div class="modal-header">
- <h4 class="modal-title">New Hiring Report</h4>
- <button type="button" class="close" data-dismiss="modal">×</button>
- </div>
- <div class="modal-body">
- <div class="row">
- <div class="col-md-4">
- <div class="form-group">
- <label>Year of hiring:</label>
- <asp:TextBox ID="txtYear" CssClass="form-control" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="rfvYear" ControlToValidate="txtYear" CssClass="text-danger" runat="server" ErrorMessage="Please enter year"></asp:RequiredFieldValidator>
- </div>
- </div>
- <div class="col-md-4">
- <div class="form-group">
- <label>Account Department:</label>
- <asp:TextBox ID="txtAccountDepartment" CssClass="form-control" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="rfvAccount" ControlToValidate="txtYear" CssClass="text-danger" runat="server" ErrorMessage="Please enter number employee hired"></asp:RequiredFieldValidator>
- </div>
- </div>
- <div class="col-md-4">
- <div class="form-group">
- <label>HR Department:</label>
- <asp:TextBox ID="txtHRDepartment" CssClass="form-control" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="rfvHR" ControlToValidate="txtHRDepartment" CssClass="text-danger" runat="server" ErrorMessage="Please enter number employee hired"></asp:RequiredFieldValidator>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-md-4">
- <div class="form-group">
- <label>IT Department:</</label>
- <asp:TextBox ID="txtITDepartment" CssClass="form-control" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="rfvIT" ControlToValidate="txtITDepartment" CssClass="text-danger" runat="server" ErrorMessage="Please enter number employee hired"></asp:RequiredFieldValidator>
- </div>
- </div>
- <div class="col-md-4">
- <div class="form-group">
- <label>Sales Department:</label>
- <asp:TextBox ID="txtSalesDepartment" CssClass="form-control" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="rfvSales" ControlToValidate="txtSalesDepartment" CssClass="text-danger" runat="server" ErrorMessage="Please enter number employee hired"></asp:RequiredFieldValidator>
- </div>
- </div>
- <div class="col-md-4">
- <div class="form-group">
- <label>Marketing Department:</label>
- <asp:TextBox ID="txtMarketingDepartment" CssClass="form-control" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="rfvMarketing" ControlToValidate="txtMarketingDepartment" CssClass="text-danger" runat="server" ErrorMessage="Please enter number employee hired"></asp:RequiredFieldValidator>
- </div>
- </div>
- </div>
- </div>
- <div class="modal-footer">
- <asp:Button ID="btnSubmit" CssClass="btn btn-primary rounded-0" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
- <button type="button" class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>
- </div>
- </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>
- <div id="chart_div" style="width: 100%; height: 400px">
- </div>
- </div>
- </form>
- </body>
Step 9
Double click on the submit button and write the following C# code.
Add the following namespace.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Script.Services;
- using System.Web.Services;
- using System.Web.UI.WebControls;
- using GoogleLineChart_Demo.Models;
Complete C# code of web form
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Script.Services;
- using System.Web.Services;
- using System.Web.UI.WebControls;
- using GoogleLineChart_Demo.Models;
-
- namespace GoogleLineChart_Demo
- {
- public partial class GooglelineChart : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- BindGridView();
- ClearTextBox();
- }
- }
-
- private void ClearTextBox()
- {
- txtYear.Text = string.Empty;
- txtAccountDepartment.Text = string.Empty;
- txtHRDepartment.Text = string.Empty;
- txtITDepartment.Text = string.Empty;
- txtSalesDepartment.Text = string.Empty;
- txtMarketingDepartment.Text = string.Empty;
- }
-
- private void BindGridView()
- {
- using (DBModel db = new DBModel())
- {
- CompanyGridView.DataSource = (from r in db.CompanyHiringReports select r).ToList();
- CompanyGridView.DataBind();
- }
- }
-
- [WebMethod]
- [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
- public static object[] GetChartData()
- {
- List<CompanyHiringReport> data = new List<CompanyHiringReport>();
- using (DBModel db = new DBModel())
- {
- data = db.CompanyHiringReports.ToList();
- }
- var chartData = new object[data.Count + 1];
- chartData[0] = new object[]{
- "Year",
- "Accounts",
- "HR",
- "IT",
- "Sales",
- "Marketing"
- };
- int j = 0;
- foreach (var i in data)
- {
- j++;
- chartData[j] = new object[] { i.Year.ToString(), i.Account, i.HR, i.IT,i.Sales,i.Marketing };
- }
- return chartData;
- }
-
- protected void btnSubmit_Click(object sender, EventArgs e)
- {
- using (DBModel db = new DBModel())
- {
- CompanyHiringReport company = new CompanyHiringReport();
- company.Year = Convert.ToInt32(txtYear.Text);
- company.Account = Convert.ToInt32(txtAccountDepartment.Text);
- company.HR = Convert.ToInt32(txtHRDepartment.Text);
- company.IT = Convert.ToInt32(txtITDepartment.Text);
- company.Sales = Convert.ToInt32(txtSalesDepartment.Text);
- company.Marketing = Convert.ToInt32(txtMarketingDepartment.Text);
-
- db.CompanyHiringReports.Add(company);
- db.SaveChanges();
- ClearTextBox();
- }
- this.BindGridView();
- }
- }
- }
Step 9
Right click on web config file and add the following code to avoid validation related errors.
- <appSettings>
- <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
- </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.