Charts In ASP.NET MVC Using Chart.js

This article demonstrates how to create charts in ASP.NET MVC using Chart.js and C#. This article starts with how to use Chart.js in your MVC project. After that, it demonstrates how to add charts in a view.

Introduction

This article demonstrates how to create charts in ASP.NET MVC using Chart.js and C#. This article starts with how to use Chart.js in your MVC project. After that, it demonstrates how to add charts to a View.

Using Chart.js in your ASP.NET MVC project (C#) 

Chart.js is a JavaScript charting tool for web developers. The latest version can be downloaded from GitHub or can use CDN.

In this article, Chart.js CDN (v2.6.0) is used for demonstration purposes.

  1. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js" type="text/javascript"></script>  

Listing 1

In the View (*.cshtml), add the Chart.js CDN along with jQuery CDN (recommended) in the head section if you haven’t mentioned those in layout pages.

  1. @section head  
  2. {  
  3.     <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js" type="text/javascript"></script>  
  4.     <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>  
  5. }  

Listing 2

Adding chart to a View

In the following example, the <canvas> tag is used to hold the chart in View’s <body> section.

  1. <div Style="font-family: Corbel; font-size: small ;text-align:center " class="row">  
  2.     <div  style="width:100%;height:100%">  
  3.             <canvas id="myChart" style="padding: 0;margin: auto;display: block; "> </canvas>  
  4.     </div>  
  5. </div>  

Listing 3

Now, in the Controller class, let’s add a method to return the data for the chart that we added in the View. In this example, we are using JSON format for the source data.

  1. [HttpPost]  
  2. public JsonResult NewChart()  
  3. {  
  4.     List<object> iData = new List<object>();  
  5.     //Creating sample data  
  6.     DataTable dt = new DataTable() ;  
  7.     dt.Columns.Add("Employee",System.Type.GetType("System.String"));  
  8.     dt.Columns.Add("Credit",System.Type.GetType("System.Int32"));  
  9.   
  10.     DataRow dr = dt.NewRow();  
  11.     dr["Employee"] = "Sam";  
  12.     dr["Credit"] = 123;  
  13.     dt.Rows.Add(dr);  
  14.   
  15.     dr = dt.NewRow();  
  16.     dr["Employee"] = "Alex";  
  17.     dr["Credit"] = 456;  
  18.     dt.Rows.Add(dr);  
  19.   
  20.     dr = dt.NewRow();  
  21.     dr["Employee"] = "Michael";  
  22.     dr["Credit"] = 587;  
  23.     dt.Rows.Add(dr);  
  24.     //Looping and extracting each DataColumn to List<Object>  
  25.     foreach (DataColumn dc in dt.Columns)  
  26.     {  
  27.         List<object> x = new List<object>();  
  28.         x = (from DataRow drr in dt.Rows select drr[dc.ColumnName]).ToList();  
  29.         iData.Add(x);  
  30.     }  
  31.     //Source data returned as JSON  
  32.     return Json(iData, JsonRequestBehavior.AllowGet);  
  33. }  

Listing 4

Source Table

EMPLOYEE CREDIT
Sam 123
Alex 456
Michael 587

Table 1

The data from the source table is processed in such a way that each column in the result table is made to separate list. The first column is expected to have the X-axis data of the chart, whereas the consequent columns hold the data for Y-axis. (Chart.js expects the Axis labels in separate list. Please check the AJAX call section.)

The data for axises is combined to a single List<Object>, and returned from the method as JSON.

AJAX calls are used in the <script> section of View to call the method in Controller to get the chart data.

  1. <script>  
  2.     $.ajax({  
  3.         type: "POST",  
  4.         url: "/Chart/NewChart",  
  5.         contentType: "application/json; charset=utf-8",  
  6.         dataType: "json",  
  7.         success: function (chData) {  
  8.         var aData = chData;  
  9.         var aLabels = aData[0];  
  10.         var aDatasets1 = aData[1];  
  11.         var dataT = {  
  12.             labels: aLabels,  
  13.             datasets: [{  
  14.                 label: "Test Data",  
  15.                 data: aDatasets1,  
  16.                 fill: false,  
  17.                 backgroundColor: ["rgba(54, 162, 235, 0.2)""rgba(255, 99, 132, 0.2)""rgba(255, 159, 64, 0.2)""rgba(255, 205, 86, 0.2)""rgba(75, 192, 192, 0.2)""rgba(153, 102, 255, 0.2)""rgba(201, 203, 207, 0.2)"],  
  18.                 borderColor: ["rgb(54, 162, 235)""rgb(255, 99, 132)""rgb(255, 159, 64)""rgb(255, 205, 86)""rgb(75, 192, 192)""rgb(153, 102, 255)""rgb(201, 203, 207)"],  
  19.                 borderWidth: 1  
  20.                 }]  
  21.             };  
  22.         var ctx = $("#myChart").get(0).getContext("2d");  
  23.         var myNewChart = new Chart(ctx, {  
  24.             type: 'bar',  
  25.             data: dataT,  
  26.             options: {  
  27.                 responsive: true,  
  28.                 title: { display: true, text: 'CHART.JS DEMO CHART' },  
  29.                 legend: { position: 'bottom' },  
  30.                 scales: {  
  31.                 xAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' } }],  
  32.                 yAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' }, ticks: { stepSize: 50, beginAtZero: true } }]  
  33.             },  
  34.         }  
  35.         });  
  36.     }  
  37. });  
  38. </script>  

Listing 5

aData[0] has the data for X-Axis labels and aData[1] has the data for Y-Axis correspondingly.

As in the code, the AJAX call is made to the Controller method ’/Chart/NewChart’ where ‘Chart’ is the name of the Controller class and ‘NewChart’ is the method which returns the source data for the chart in JSON format.

AJAX call, when returned successfully, processes the returned JSON data.

The JSON data is processed to extract the labels and axis data for the chart preparation. The 2D context of the canvas ‘myChart’ is created using ‘getContext("2d")’ method, and then the context is used to create the chart object in ‘new Chart()’ method inside the script.

Result chart in view

MVC
Figure 1

Chart type, legends, color, step-size etc. can be changed and controlled in the ‘new Chart()’ function of the AJAX script.

Please refer to the Chart.js documentation for the explanations of different keywords used for chart effects/properties, as it will be out of the scope of this article.

Summary

In this article, I discussed how we can create a chart in ASP.NET MVC using Chart.js and C#.  We also saw how we can add a chart to a View and fetch the data from Controller to the chart in View.