Dynamic am-Charts In ASP.NET MVC

Here, we will learn about creating dynamic am-charts in ASP.NET MVC 5. Charts are very useful for seeing how much work is done in any place in a short period of time.
 
Prerequisites
  • Basic knowledge of jQuery.
  • Data from which we can generate the charts.
Create a new project in ASP.NET MVC.
 
We are going to use the following jQuery libraries provided by amCharts.
  1. <script src="https://www.amcharts.com/lib/4/core.js"></script>    
  2. <script src="https://www.amcharts.com/lib/4/charts.js"></script>     
  3. <script src="https://www.amcharts.com/lib/4/plugins/forceDirected.js"></script>    
  4. <script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>     
We are going to use the dummy API for the chart data.
  1. https://api.myjson.com/bins/zg8of 
Open the View -> Home -> Index.cshtml and write the code for generating the chart.
  1. @{    
  2.     ViewBag.Title = "AM Chart Demo";    
  3. }    
  4.     
  5. <div id="chartData"></div>    
  6.     
  7. @Scripts.Render("~/bundles/jquery")    
  8.     
  9. <script src="https://www.amcharts.com/lib/4/core.js"></script>    
  10. <script src="https://www.amcharts.com/lib/4/charts.js"></script>    
  11. <script src="https://www.amcharts.com/lib/4/plugins/forceDirected.js"></script>    
  12. <script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>    
  13.     
  14. <script>    
  15.     $(document).ready(function () {    
  16.         $.ajax({    
  17.             url: 'https://api.myjson.com/bins/zg8of',    
  18.             method: 'GET', success: function (data) {    
  19.                 generateChart(data);    
  20.             }, error: function (err) {    
  21.                 alert("Unable to display chart. Something went wrong.");    
  22.             }    
  23.         });    
  24.     
  25.         function generateChart(data, iteration = 0) {    
  26.             var dates = [];    
  27.             var newData = [];    
  28.             var gr = [];    
  29.     
  30.             function groupBy(array, f) {    
  31.                 var groups = {};    
  32.                 array.forEach(function (o) {    
  33.                     var group = JSON.stringify(f(o));    
  34.                     groups[group] = groups[group] || [];    
  35.                     groups[group].push(o);    
  36.                 });    
  37.                 return Object.keys(groups).map(function (group) {    
  38.                     return groups[group];    
  39.                 })    
  40.             }    
  41.             var result = groupBy(data, function (item) {    
  42.                 return ([item.Name]);    
  43.             });    
  44.             $.each(result, function (a, b) {    
  45.                 var d1 = b.map(function (i) {    
  46.                     return i.Month;    
  47.                 });    
  48.                 $.extend(true, dates, d1);    
  49.             });    
  50.             $.each(dates, function (a, b) {    
  51.                 var item = {    
  52.                     sales_figure: b    
  53.                 };    
  54.                 $.each(result, function (i, c) {    
  55.                     el = c.filter(function (e) {    
  56.                         return e.Month == b;    
  57.                     });    
  58.                     if (el && el.length > 0) {    
  59.                         item[c[i].Name.toUpperCase()] = el[0].Sales_Figure;    
  60.                         if (gr.filter(function (g) {    
  61.                             return g == c[i].Name.toUpperCase();    
  62.                         }).length <= 0) {    
  63.                             gr.push(c[i].Name.toUpperCase());    
  64.                         }    
  65.                     }    
  66.                 });    
  67.                 if (Object.keys(item).length > 1) newData.push(item);    
  68.             });    
  69.             $chartData = $('#chartData');    
  70.             var am_el = $('<div id="dc-' + iteration + '" class="col-md-12 col-xs-12 card-item">');    
  71.             am_el.append($('<div class="lgnd col-md-12 col-xs-12 bb2"><div id="l-' + iteration + '" class="col-md-12 col-xs-12"></div></div>'));    
  72.             am_el.append($('<div id="c-' + iteration + '" class="col-md-12 col-xs-12" style="min-height:250px ; margin-left: -8px;">'));    
  73.             $chartData.html(am_el);    
  74.             var chart = am4core.create("c-" + iteration, am4charts.XYChart);    
  75.             am4core.options.minPolylineStep = Math.ceil(newData.length / 50);    
  76.             am4core.options.commercialLicense = true;    
  77.             am4core.animationDuration = 0;    
  78.             chart.data = newData;    
  79.             var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());    
  80.             categoryAxis.dataFields.category = "sales_figure";    
  81.             categoryAxis.renderer.minGridDistance = 70;    
  82.             categoryAxis.fontSize = 12;    
  83.             var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());    
  84.             valueAxis.fontSize = 12;    
  85.             valueAxis.title.text = "Sales Figure";    
  86.             chart.legend = new am4charts.Legend();    
  87.             chart.legend.position = "top";    
  88.             chart.legend.fontSize = 12;    
  89.             var markerTemplate = chart.legend.markers.template;    
  90.             markerTemplate.width = 10;    
  91.             markerTemplate.height = 10;    
  92.             var legendContainer = am4core.create("l-" + iteration, am4core.Container);    
  93.             legendContainer.width = am4core.percent(100);    
  94.             chart.legend.parent = legendContainer;    
  95.             var legendDiv = document.getElementById("l-" + iteration);    
  96.     
  97.             function resizeLegendDiv() {    
  98.                 legendDiv.style.height = chart.legend.measuredHeight + "px";    
  99.                 legendDiv.style.overflow = "hidden";    
  100.             }    
  101.             chart.legend.events.on('inited', resizeLegendDiv);    
  102.             chart.colors.list = [am4core.color("#0D8ECF"), am4core.color("#FF6600"), am4core.color("#FCD202"), am4core.color("#B0DE09"), am4core.color("#2A0CD0"), am4core.color("#CD0D74"), am4core.color("#CC0000"), am4core.color("#00CC00"), am4core.color('#ffd8b1'), am4core.color("#990000"), am4core.color('#4363d8'), am4core.color('#e6194b'), am4core.color('#3cb44b'), am4core.color('#ffe119'), am4core.color('#f58231'), am4core.color('#911eb4'), am4core.color('#46f0f0'), am4core.color('#f032e6'), am4core.color('#bcf60c'), am4core.color('#fabebe'), am4core.color('#008080'), am4core.color('#e6beff'), am4core.color('#9a6324'), am4core.color('#fffac8'), am4core.color('#800000'), am4core.color('#aaffc3'), am4core.color('#808000'), am4core.color('#ffd8b1'), am4core.color('#000075')] $.each(gr, function (l, d) {    
  103.                 var series = chart.series.push(new am4charts.LineSeries());    
  104.                 series.dataFields.valueY = d;    
  105.                 series.name = d;    
  106.                 series.dataFields.categoryX = "sales_figure";    
  107.                 series.tooltipText = "{name}: [bold]{valueY}[/]";    
  108.                 series.strokeWidth = 2;    
  109.                 series.minBulletDistance = 30;    
  110.                 series.tensionX = 0.7;    
  111.                 series.legendSettings.labelText = "[bold]" + "{name}";    
  112.                 var bullet = series.bullets.push(new am4charts.CircleBullet());    
  113.                 bullet.circle.strokeWidth = 2;    
  114.                 bullet.circle.radius = 3;    
  115.                 bullet.circle.fill = am4core.color("#fff");    
  116.                 var bulletbullethover = bullet.states.create("hover");    
  117.                 bullethover.properties.scale = 1.2;    
  118.                 chart.cursor = new am4charts.XYCursor();    
  119.                 chart.cursor.behavior = "panXY";    
  120.                 chart.cursor.snapToSeries = series;    
  121.             });    
  122.             chart.scrollbarX = new am4core.Scrollbar();    
  123.             chartchart.scrollbarX.parent = chart.bottomAxesContainer;    
  124.         }    
  125.     
  126.     });    
  127. </script>    
Output
 
You can download the source code from here.
 
Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.


Similar Articles