Dec 18

Display Organization or Tree Structure using Google Charts and ASP.NET MVC

1. Introduction

Chart is also called as graph and it is graphical representation of data. Chart can usually be read more quickly than the row data. Chart is the greatest and simplest way to express data to user or management persons. Charts are very common in all type of business requirement. In one of my assignment there were the functionality of organization chart display. I googled and explored various approaches to find the solution and found interesting article on google i.e. Google Charts. The google chart tools are powerful and easy to use. Google also provides different type of rich gallery of interactive charts and data tools.
In this article I will explain how googles organization chart tool useful for displaying organizational chart using ASP.NET MVC.

Click here to view basic concept of Charts. The Overview section will explain The details about various parts or concepts of a chart.

2. Overview

In my careers starting days with ASP.NET, I remember we used different type of third party control to implement chart functionality in applications. But now using different open source library provides inbuilt support for different Chart in a very simpler fashion. The Google Charts shows how we can display organization chart in very simpler manner .
Google charts provides a perfect way to visualize data on your website. The google chart gallery provides number of ready-to-use chart types. The most common way to use Google Charts is with simple JavaScript that you embed in your web page. You load some Google Chart libraries, list the data to be charted, select options to customize your chart, and finally create a chart object with an id that you choose. Then, later in the web page, you create a <div> with that id to display the Google Chart. Google Charts are rendered using HTML5/SVG technology to provide cross-browser compatibility (including VML for older IE versions) and cross platform portability to iPhones, iPads and Android.
All chart types are populated with data using the DataTable class, making it easy to switch between chart types as you experiment to find the ideal appearance. The DataTable provides methods for sorting, modifying, and filtering data, and can be populated directly from your web page, a database, or any data provider supporting the Chart Tools Datasource protocol.
It uses below simple steps.
1. Load AJAX API library from Google Chart website
2.       Load the Visualization API and the required package.
3.       Set a callback to run when the Google Visualization API is loaded.
4.       Callback that creates and populates a data table, instantiates the required chart, passes in the data and draws it.
5.       Create the data table.
6.       Set chart options
7.       Instantiate and draw our chart, passing in some options.
8.       Create Div that will hold the required chart

3. Practical Implementation

There are multiple ways to achieve charting functionality. You can create chart using arrays, database query or using xml data. Below example explains how to create chart using json arrays result.
Step 1:
Download the loader.js javascript library to your project or you give reference of this library in your aspx page.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
Step 1: Download library to your projects script folder and create bundle in BundleConfig.cs file.
bundles.Add(new ScriptBundle(“~/bundles/googleOrgChart”).Include(
“~/Scripts/OrgChart/loader.js”));
Step 2: Create Razor engine view page and refer the above bundle file.
@{
    ViewBag.Title = “Google Organization Chart”;
}

@Scripts.Render(“~/bundles/googleOrgChart”)

<div id=”orgChartDiv”></div>


Step 3: Create or write javascript and refer on page.
<script type=”text/javascript”>
     $(document).ready(function () {
         drawOrgChartAjax();
     });
     // Declare veriable to hold data
     varjsonResult = [];
     functiondrawOrgChartAjax() {
         $.ajax({
             type: “GET”,
             contentType: “application/json; charset=utf-8”,
             url: “OrgChart/DrawOrgChart”,
             data: “{}”,
             dataType: “json”,
             cache: true,
             success: function (result) {
                 jsonResult = result;
                 google.charts.load(‘current’, { packages: [“orgchart”] });
                 google.charts.setOnLoadCallback(drawOrgChart);
             },
             error: function (result) {
                 alert(“Error”);
             }
         });
     }
     functiondrawOrgChart() {
         //Object structure
         var data = newgoogle.visualization.DataTable();
         data.addColumn(‘string’, ‘Name’);
         data.addColumn(‘string’, ‘Manager’);
         data.addColumn(‘string’, ‘ToolTip’);
         // Loop through the resultset
         $.each(jsonResult, function (key, jsonObj) {
             data.addRows([([{ v: jsonObj.EmployeeName, f: jsonObj.EmployeeName + ‘<div style=”color:red; font-style:italic”>’ + jsonObj.Role + ‘</div>’ }, jsonObj.ManagerName, jsonObj.Role])]);
         });
         // Create the chart.
         var chart = newgoogle.visualization.OrgChart(document.getElementById(‘orgChartDiv’));
         // Draw the chart, setting the allowHtml option to true for the tooltips.
         chart.draw(data, { allowHtml: true });
     }
   </script>
 
Step 4: Create appropriate model to display data
public class OrganizationChartModel
{
      public string EmployeeName { get; set; }
      public string ManagerName { get; set; }
      public string Role { get; set; }
      public string ClassStyle { get; set; }
}
Step 5: Create controller file and create action do display result.

public ActionResult Index()
{
       return View();
}

public JsonResult DrawOrgChart()
{
            varorgChartModel = new List<OrganizationChartModel>
            {
                new OrganizationChartModel { EmployeeName= “Arun”, ManagerName = “”, Role = “Chif Executive Officer”},
                new OrganizationChartModel { EmployeeName= “Deepak”, ManagerName = “Arun”, Role = “Chif Operating Officer”},
                new OrganizationChartModel { EmployeeName= “Jaikrishna”, ManagerName = “Arun”, Role = “Chif Technical Officer”},
                new OrganizationChartModel { EmployeeName= “Raghav”, ManagerName = “Jaikrishna”, Role = “Principal Architect(Microsoft)”, },
                new OrganizationChartModel { EmployeeName= “Santosh”, ManagerName = “Jaikrishna”, Role = “Principal Architect(Java)”},
                new OrganizationChartModel { EmployeeName= “Prachi”, ManagerName = “Jaikrishna”, Role = “Principal Architect(Open Source)”},
                new OrganizationChartModel { EmployeeName= “Amit”, ManagerName = “Raghav”, Role = “Sr Architect”},
                new OrganizationChartModel { EmployeeName= “Prashant”, ManagerName = “Raghav”, Role = “Sr Architect”},
                new OrganizationChartModel { EmployeeName= “Kavita”, ManagerName = “Amit”, Role = “Architect”},
                new OrganizationChartModel { EmployeeName= “Rohit”, ManagerName = “Amit”, Role = “Architect”},
            };
            returnJson(orgChartModel, JsonRequestBehavior.AllowGet);
}
 
Step 6: Now, run the application to display organization chart

 



















I hope you enjoyed the sample code that I provided. I would suggest you to play something around the code and theme.

4. Summary

Using Google Chart tool, it is very easy to show chart in your ASP.NET MVC application. In this article, I showed you how to create a chart in ASP.NET MVC. I also showed you how to style a chart and how to change the background color of a chart. Hopefully you will enjoy this article too. In my next blog post article, I will explain how Google Visualization Chart tools are useful to display Bar, Pie and Donut Charts in ASP.NET MVC.

5. Download Code

 

Click here to download the source code of this assignment.

Leave a Reply