Organizational Chart In ASP.NET MVC Using Google API

Introduction
 
Recently, I came across a requirement to display all the employees with basic info(name, designation) in hierarchical ways. I found Google Organizational chart is suitable to accomplish the requirement. Here we will discuss how to implement Organizational chart in ASP.NET MVC, using Google JS API.
 
Using Code
 
To implement an organizational chart requirement, we divide it into 3 modules:
  1. Database design.
  2. Design controller/model to retrieve data from DB.
  3. Design view to display chart using Google chart.
Database Design
 
Let's design a table, which will keep information about an employee. SQL query, given below, is used to create table(tblEmployee) with the required columns ID like FirstName, LastName, Designation, Email and ReportID etc.
  1. CREATE TABLE [dbo].[tblEmployee](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [FirstName] [varchar](50) NULL,  
  4.     [LastName] [varchar](50) NULL,  
  5.     [Designation] [varchar](50) NULL,  
  6.     [Email] [varchar](50) NULL,  
  7.     [Address] [varchar](maxNULL,  
  8.     [ReportID] [intNULL,  
  9.     [IsActive] [bitNULL,  
  10.  CONSTRAINT [PK_tblEmployee] PRIMARY KEY CLUSTERED   
  11. (  
  12.     [Id] ASC  
  13. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF
  14.    ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  15. ON [PRIMARY]  
Next action is to insert the employee records with the required information like ID, FirstName, ReportID, Designation etc. The snapshot, given below, shows the employee records:
 
                              Figure 1: Employee Records
 
Design Controller and Model
 
Once we complete the database part, it's time to focus on the Application side(model and controller design).
 
Model
 
Add model(Employee.cs), given below, in Model folder with properties ID, first name, last, designation, Email, report ID etc. 
  1. public class Employee  
  2. {  
  3.     public int Id { getset; }  
  4.     public string FirstName { getset; }  
  5.     public string LastName { getset; }  
  6.     public string Designation { getset; }  
  7.     public string Email { getset; }  
  8.     public int ReportID { getset; }  
  9.     public bool IsActive { getset; }  
  10. }  
Controller
 
In a controller, add an action, which retrieves the Employee records and returns the data in JSON format. Here, I have used simple ADO.NET to get the data. You can use EntityFramework, if you want. 
  1. [HttpPost]  
  2. public JsonResult GetEmpChartData()  
  3. {  
  4.     List<Employee> empChartList = new List<Employee>();  
  5.   
  6.     string query = "SELECT Id, FirstName, Designation, Email, ReportID";  
  7.     query += " FROM tblEmployee";  
  8.     
  9.     // Get it from Web.config file
  10.     string connetionString = "Data Source=MyPC\\SQLEXPRESS;Initial Catalog=AllTest;Integrated Security=True;";  

  11.     using (SqlConnection con = new SqlConnection(connetionString))  
  12.     {  
  13.         using (SqlCommand cmd = new SqlCommand(query))  
  14.         {                     
  15.             cmd.CommandType = CommandType.Text;  
  16.             cmd.Connection = con;  
  17.             con.Open();  
  18.             using (SqlDataReader dr = cmd.ExecuteReader())  
  19.             {  
  20.                 while (dr.Read())  
  21.                 {  
  22.                      // Adding new Employee object to List
  23.                     empChartList.Add(new Employee()  
  24.                     {  
  25.                         Id = dr.GetInt32(0),  
  26.                         FirstName = dr.GetString(1),  
  27.                         Designation = dr.GetString(2),  
  28.                         Email = dr.GetString(3),  
  29.                         ReportID = dr.IsDBNull(4) ? 0 : dr.GetInt32(4)  
  30.                     });  
  31.                 }  
  32.             }  
  33.             con.Close();                      
  34.         }  
  35.     }  
  36.   
  37.     return Json(empChartList, JsonRequestBehavior.AllowGet);  
  38. }  
Regarding View, we will discuss in the next module, because it needs JavaScript, Google chart, HTML code etc. and thus, it is better to see in the next module.
 
Design View to display chart 
 
In View, there is a DIV, where the data will render as a chart in the hierarchical way.
 
Add DIV, given below:
  1. <div id="empChart">  
  2. </div>  
The code snippet, given below, is to send an AJAX request, which retrieves all the employee records. It loops over the records and binds to the chart object.
  1. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>  
  2. <script type="text/javascript" src="https://www.google.com/jsapi"></script>  
  3.   
  4. <script type="text/javascript">  
  5.     google.load("visualization""1", { packages: ["orgchart"] });  
  6.   
  7.     $('#btnLoadChart').click(function () {  
  8.         drawEmpChart();  
  9.     });  
  10.   
  11.     function drawEmpChart() {
  12.   
  13.         $.ajax({  
  14.             type: "POST",  
  15.             url: "Home/GetEmpChartData",  
  16.             data: '{}',  
  17.             contentType: "application/json; charset=utf-8",  
  18.             dataType: "json",  
  19.             success: function (empData) { 
  20.   
  21.                 var chartData = new google.visualization.DataTable();  
  22.   
  23.                 chartData.addColumn('string''Name');  
  24.                 chartData.addColumn('string''Manager');  
  25.                 chartData.addColumn('string''ToolTip');  
  26.   
  27.                 $.each(empData, function (index, row) {  
  28.                     var reportID = row.ReportID.toString() == "0" ? '' : row.ReportID.toString();  
  29.   
  30.                     chartData.addRows([[{  
  31.                         v: row.Id.toString(),  
  32.                         f: row.FirstName + '<div>(<span>' + row.Designation + '</span>)</div><img height="50px" width="50px" src = "Photos/' + row.Id.toString() + '.jpg" />'  
  33.                     }, reportID, row.Designation]]);  
  34.                 });  
  35.   
  36.                 var chart = new google.visualization.OrgChart($("#empChart")[0]);  
  37.                 chart.draw(chartData, { allowHtml: true });  
  38.             },  
  39.             failure: function (xhr, status, error) {  
  40.                 alert("Failure: " + xhr.responseText);  
  41.             },  
  42.             error: function (xhr, status, error) {  
  43.                 alert("Error: " + xhr.responseText);  
  44.             }  
  45.         });  
  46.     }  
  47. </script>  
Preceding code description
 
1. Add two JavaScript CDN references, one for jQuery and another one is for Google JS API.
 
2. First step is to load Google Organizational Chart API packages.
 
3. Send jQuery AJAX call to get the records from the database as list of Employee. Once the AJAX response is received, an object of Google Visualization DataTable is created. Google Visualization DataTable must contain three columns in order to populate an organizational chart.
 
Note: You can set any name of your choice to the columns. I have given the name as of understanding.
  • Name – This column stores the object of the Entity or Node in the organization chart. This object consists of two properties:

    • v – It stores the unique identifier of the Entity or Node. In this example, it is ID.
    • f – It stores the formatting details of the Entity or Node. In this example,I have displayed Employee Name on top, followed by Designation and finally the picture of the Employee.
  • Manager – This column denotes ID of parent node to display records in hierarchical way, i.e. ReportID(Reporting Manager ID). It is very important to find the parent of a particular Node. If left blank, the Node will be considered as a Root Node(default).
  • ToolTip – This column stores to show ToolTip or Title attribute to the Node. If you don’t want to display ToolTip, leave it blank. Finally, a loop is executed and one by one, by the records are inserted into the Google Visualization DataTable which is then used for draw the chart on to the specified HTML DIV element. 
Figure 2 shows Organizational chart in hierarchical ways.
 
 
         Figure 2: Organizational Chart
  
Conclusion
 
In this article, we discussed organization chart, using Google JS in ASP.NET MVC. You can use this chart in many scenarios, like program flow chart, employee hierarchy etc.


Similar Articles