In this tutorial dedicated to junior developers, I want to demostrate the simplicity of Blazor compared to MVC and WebForms. In this tutorial, we will be based on this code : https://www.aspsnippets.com/Articles/Create-Family-Tree-Hierarchy-Chart-from-Database-in-ASPNet-using-C-and-VBNet.aspx.
Full source code is here :https://github.com/desalbres/FamilyHierarchy and demo here : https://blazordemos.exceldev.com/
First we must register Google Chart in our page _Host.cshtml.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
Then we have our base class:
public class Hierarchy { public int MemberId { get; set; } public string Name { get; set; } public int? ParentId { get; set; } }Then our dummy data collection:
public class Hierarchies { public List<Hierarchy> data { get { return new List<Hierarchy> { new Hierarchy { MemberId= 1, Name= "Nancy Davolio", ParentId = 4 }, new Hierarchy { MemberId= 2, Name= "Andrew Fuller", ParentId = 4 }, new Hierarchy { MemberId= 3, Name= "Janet Leverling", ParentId = 4 }, new Hierarchy { MemberId= 4, Name= "Margaret Peacock", ParentId = null }, new Hierarchy { MemberId= 5, Name= "Steven Buchanan", ParentId = 3 }, new Hierarchy { MemberId= 6, Name= "Michael Suyama", ParentId = 3 }, new Hierarchy { MemberId= 7, Name= "Robert King", ParentId = 2 }, new Hierarchy { MemberId= 8, Name= "Laura Callahan", ParentId = 2 }, new Hierarchy { MemberId= 9, Name= "Anne Dodsworth", ParentId = 2 } }; } } }
In our base page, we must call a javascript interop to show Google Chart.
@page "/" @inject IJSRuntime JsRuntime <h1>Hello, world!</h1> Welcome to your new app. <div id="chart"> </div> @functions { protected override async Task OnAfterRenderAsync() { var hierarchies = new Data.Hierarchies(); var data = hierarchies.data; await JsRuntime.InvokeAsync<Task>("drawChart", data); } }
And, finaly the javascript code. It's important to notice that we dont' have to serialize any code.
window.drawChart = (data) => { google.load("visualization", "1", { packages: ["orgchart"] }); google.setOnLoadCallback(drawGoogleChart); function drawGoogleChart() { var dt = new google.visualization.DataTable(); dt.addColumn('string', 'Entity'); dt.addColumn('string', 'ParentEntity'); dt.addColumn('string', 'ToolTip'); for (var i = 0; i < data.length; i++) { var memberId = data[i].memberId.toString(); var memberName = data[i].name; var parentId = data[i].parentId != null ? data[i].parentId.toString() : ''; dt.addRows([[{ v: memberId, f: memberName + '<div><img src = "img/' + memberId + '.jpg" /></div>' }, parentId, memberName]]); } var chart = new google.visualization.OrgChart(document.getElementById("chart")); chart.draw(dt, { allowHtml: true }); } };
And that's all, folks!!!