Graphs In ASP.NET MVC Using HighCharts

Firstly, we will learn how to fetch your data from a database (here we will use MsSql ) and then present it in the View using HighCharts.
 
To understand the complete article, you must have basic knowledge/understanding about the below mentioned technologies/ methods,
  • Asp.Net MVC.
  • MSSQL Server.
  • JavaScript
  • JSON (JavaScript Object Notation).
  • ADO.Net
  • Entity Framework
We will be using HighCharts for representing our record as chart/graph (given at the end of the article).
 

What is HighCharts?

 
Highcharts is a charting library written in pure JavaScript, offering an easy way of adding interactive charts to your web site or web application. In the vast majority of charts we will be using a basic column chart here to represent our data.
 
You can visit here to check more variety and select which is best for your scenario.
 
Steps 1 - Creating a basic Asp.Net MVC Web Based Application.
 
Create an Application in ASP.NET MVC web application using Visual Studio.
 
Go to File Menu > New > Project.
 
Select ASP.NET Web Application ( .NET Framework ) and change the application name:
 
e.g. : HighCharts, and then click OK
 
Choose MVC>
 
Now, the MVC web application project is created with the default ASP.NET MVC template.
 
Step 2 - Create/Step up your DataBase and Table.
 
Here, we are using an existing MsSql Database of a “Grievance Portal” and a table (T_Complaint) which stores the data of the person from whom the Complaint has been received and we will show the same number of applications which are received by year,  by grouping them by years of application received and then sorting them by year.
 
The Structure of the table (T_Complaint) is as Below,
 
S. No
Column Name
Data Type
Description
1
ComplaineName
nvarChar(50)
Name of the complaint
2
ComplainLetterDate
DateTime
Application received date
3
ComplainNumber
Number
Primary Key for Complaint no.
4.
Concluded
Boolean
True when complaint is Resolved.
Many more…
 
There will be many more columns like address, district, state, father’s name, complaint description, but as of now the above-mentioned columns are enough for our task.
 
Since the data that we will fetch could be huge here we are using “Stored Procedure” to retrieve it by just calling it from the controller as Stored Procedures take less time to fetch a huge amount of data as compared to SQL queries.
 
The below code will help you to create a Stored procedure.
  1. Create PROCEDURE [dbo].[SP_YearlyRec]  
  2. AS  
  3.   
  4. select sum(Total)as 'Total',max(t1.concluded)as concluded,MAX(t1.Not_concluded)as Not_concluded,Complainletteryear from (  
  5. select count(Complainletterdate) as 'Total',case when Conclusion=1 then count(year(Complainletterdate))end as concluded,  
  6. case when Conclusion=0 then count(year(Complainletterdate)) else 0 end as Not_concluded,YEAR(Complainletterdate) as [Complainletteryear] from T_Complaint  
  7. where Complainletterdate is not null  
  8. group by year(Complainletterdate),Conclusion  
  9. )t1 group by t1.Complainletteryear order by t1.Complainletteryear.  
The output of the above created SP will be as below,
 
Graphs In ASP.NET MVC Using HighCharts
 
Step 3 - Working on Controller
 
Here we will use the default HomeController that is created automatically when we create a new MVC application.
 
In the HomeController we will use default Index() ActionMethod and modify it as per our need or you can also create a new ActionMethod for yourself.
  1. public ActionResult Index()  
  2. {  
  3.    return View();  
  4. }  
Now create a view for your ActionMethod and give it the same name as your ActionMethod.
 
<view code is given below>
 
Next, we will create the WebMethod where we will call the Stored procedure which we have created previously.
  1. [WebMethod]  
  2. public JsonResult GetText() {  
  3.     var db1 = new Grievance_Entities1();  
  4.     var list = db1.SP_YearlyRec();  
  5.     return Json(list.ToList(), JsonRequestBehavior.AllowGet);  
  6. }  
In the above code, Grievance_Entities1 is the entity we have created of our database which has a Stored Procedure “SP_YearlyRec” using Entity Framework.
 
Once it is created, open the index view and write the below code in the view.
 
We are dividing the View/HTML Code in 3 parts, Which are,
 
Head
 
The Head Will contain the links to HighCharts important Library as well as the styling of the complete graph inside a style tag . Every change in our design of our HighCharts need to be done here only in the Style tag itself.
 
Body
 
The body tag will contain the body of our HTML page which is HighCharts Graph in this Case.
  1. <div class="container">  
  2.     <h2 id="h2">Index</h2>  
  3.     <figure class="highcharts-figure container" >  
  4.         <div id="container-fluid" class="container-fluid"></div>  
  5.         <p class="highcharts-description">  
  6.             A basic column chart .  
  7.         </p>  
  8.     </figure>  
  9. </div>  
Script 
 
The Script tag will be the functioning body of our View as here we will use Ajax to fetch our data from the database by calling the WebMethod which is in our HomeController and will return Json Result as an output.
 
As this is the most important part of our module so I will be explaining the working of this module.
 
The javascript here has two parts first is the $(document).ready() ,and the other is a function which we have created that is LoadChart().
 
$(document).ready() is automatically triggered when the document is loaded. Whatever code we write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
 
So, here we will call the WebMethod in our controller using Ajax which is GetText using URL format “../{ControllerName}/{MethodName}”. And if the data is fetched correctly then we will call the LoadChart() function to Load the HighCharts with the fetched data.
 
Below is the code that will be placed in $(document ). ready() method.
  1. $(document).ready(function() {  
  2.             var Complainletteryear = [];  
  3.             var Total = [];  
  4.             var concluded = [];  
  5.             var N_concluded = [];  
  6.             $.ajax({  
  7.                 type: "POST",  
  8.                 url: "../Home/GetText",  
  9.                 data: "{}",  
  10.                 contentType: "application/json; charset=utf-8",  
  11.                 dataType: "json",  
  12.                 async: true,  
  13.                 success: function(result) {  
  14.                     $.each(result, function(key, item) {  
  15.                         Complainletteryear.push(item.Complainletteryear);  
  16.                         Total.push(item.Total);  
  17.                         concluded.push(item.concluded);  
  18.                         N_concluded.push(item.Not_concluded);  
  19.                     });  
  20.                     loadChart(Complainletteryear, Total, concluded, N_concluded);  
  21.                 },  
  22.                 error: function(errormessage) {  
  23.                     $('#h2').html(errormessage.responseText);  
  24.                     return false;  
  25.                 }  
  26.             });  
In the above code, after the data is fetched we are selecting each Row using the foreach loop and putting every column in a specific array as the data accepted by HighCharts is either in the form of Array or Objects. In our case we need our data in the form of array. Refer to foreach loop in the above code.
 
Below we can see the Code where we will be working with HighCharts.
  1. function loadChart(category, val2, val3, val4) {  
  2.     Highcharts.chart('container-fluid', {  
  3.             chart: {  
  4.                 type: 'column',  
  5.             },  
  6.             title: {  
  7.                 text: 'No. of Application Received yearly '  
  8.             },  
  9.             subtitle: {  
  10.                 text: 'Source: LocalDb.com'  
  11.             },  
  12.             xAxis: {  
  13.                 categories: category,  
  14.                 crosshair: true  
  15.             },  
  16.             yAxis: {  
  17.                 min: 0,  
  18.                 title: {  
  19.                     text: 'Number of Application'  
  20.                 }  
  21.             },  
  22.             tooltip: {  
  23.                 headerFormat: '<span style="font-size:10px">{point.key}</span><table>',  
  24.                 pointFormat: '<tr href="#"><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y} </b></td></tr>',  
  25.                 footerFormat: '</table>'  
  26.             },  
  27.             shared: true,  
  28.             useHTML: true  
  29.         }, series: [{  
  30.             name: 'Total',  
  31.             data: val2,  
  32.             color: '#ccb1fc',  
  33.         }, {  
  34.             name: 'Concluded',  
  35.             data: val3,  
  36.             color: '#b0ceff',  
  37.         }, {  
  38.             name: 'Not Concluded',  
  39.             data: val4,  
  40.             color: '#fcb1f0'  
  41.         }]  
  42.     });  
  43. }  
In the above code, we have 4 input parameters which are category, val2,val3,val4.
 
Each variable is of array type which represents each column provided as an output from our stored procedure.
 
The variable category here defines X-Axis Categories which will be shown in the chart as a category for each column. The remaining three arrays consist of data which is to be represented as a vertical bar in each column.
 
The title here defines the  title of the Chart/Graph.
 
Chart Type tells what chart we will be using in the module.
 
Below is the figure which shows the output after implementing the above HighCharts code in Asp.Net MVC
 
Graphs In ASP.NET MVC Using HighCharts
 

Conclusion

 
To conclude , HighCharts are a user friendly graphical representation of data which can easily be represented using the above implementation in Asp.Net MVC application.
Hope the article is useful and easy to understand. For queries post your comments in the box below.