Creating Charts in ASP.Net MVC

Highcharts is a JavaScript library for charting. It draws beautiful charts with a variety of chart options and CSS options and is interactive with dynamic charts and animations. We will be using Highcharts in MVC.

Please visit the following URL for all the chart demos of Highcharts:

http://www.highcharts.com/demo/

You will get all the chart options.

Approach I: To use these charts in MVC we just need a JavaScript file and provide appropriate data.

Approach II: Another option is using the DotNet.HighChart DLL and creating object of Highcharts in the controller and setting all the properties and return this object to the view for rendering.

For this approach please visit the following URL and download the code for the implementation of this approach.

https://dotnethighcharts.codeplex.com/

We will now begin for the first approach. I will create a sample Transport database and a table with vehicle category. We will display the pie chart with the vehicle type with their number as shown below:



With the option to export this chart:



Create a MVC internet project.



Let's create a database and a table with some sample data:





After the database is created, expand the database and add a table.



Now add three columns or use the following script:


  1. CREATE TABLE [dbo].[VehicleMaster]  
  2. (  
  3.     [Id] INT NOT NULL PRIMARY KEY IDENTITY,   
  4.     [vehicleType] NVARCHAR(50) NULL,   
  5.     [vehicleNumber] NVARCHAR(50) NULL  
  6. )  




I have manually inserted a few records into the database as in the following:



The following query gives us the expected summary with percentages:

Please ignore that since I will be writing all the Data Access and models in the controller class. You can arrange the code to achieve MVC.

The following is the ADO code to get the summary from the database:

  1. public static DataTable GetVehicleSummary()  
  2. {  
  3.     DataTable dt = new DataTable("VehicleSummary");  
  4.     string query = "Select Vehicletype,str(count(Vehicletype)* 100.0 / (Select Count(*) From VehicleMaster), 5,1) as percentage ";  
  5.     query+="from VehicleMaster group by Vehicletype";  
  6.     SqlConnection con = new SqlConnection();  
  7.     con.ConnectionString = "Data Source=.;" + "Initial Catalog=Transport;" + "Persist Security Info=True;";  
  8.     SqlCommand cmd = new SqlCommand();  
  9.     cmd.CommandText = query;  
  10.     cmd.Connection = con;  
  11.     SqlDataAdapter da = new SqlDataAdapter(cmd);  
  12.     con.Open();  
  13.     da.Fill(dt);  
  14.     con.Close();  
  15.     return dt;  
  16. }  

Now we will create a model to hold this data and it to the controller:

  1. public class Summary  
  2. {  
  3.     public double Item { getset; }  
  4.     public string Value { getset; }  
  5. }  

After this we will create an Action method with JSON Result as the action result. This method will return the summary to the view to display:

  1. [HttpGet]  
  2. public JsonResult VehicleSummary()  
  3. {  
  4.     List<Summary> lstSummary = new List<Summary>();  
  5.   
  6.     foreach (DataRow dr in GetVehicleSummary().Rows)  
  7.     {  
  8.         Summary summary = new Summary();  
  9.         summary.Value = dr[0].ToString().Trim();  
  10.         summary.Item = Convert.ToDouble(dr[1]);  
  11.         lstSummary.Add(summary);  
  12.   
  13.     }  
  14.     return Json(lstSummary.ToList(), JsonRequestBehavior.AllowGet);  
  15. }  
The final code is as in the following:

Now to use the HighChart we need to include two libraries. These libraries will do the magic.

Adding the Libraries to the Layout page as in the following:
  1. <script src="http://code.highcharts.com/highcharts.js"></script>  
  2. <script src="http://code.highcharts.com/modules/exporting.js"></script>  
And add the latest jQuery CDN:
  1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>   
And comment the Script.Render jQuery bundle.

Finally the View. Now go to the view of the Index Action Method and add the following script:

  1. <script type="text/javascript">  
  2.         $(function () {  
  3.             $.ajax({  
  4.                 url: 'Home/VehicleSummary',  
  5.                 dataType: "json",  
  6.                 type: "GET",  
  7.                 contentType: 'application/json; charset=utf-8',  
  8.                 async: false,  
  9.                 processData: false,  
  10.                 cache: false,  
  11.                 delay: 15,  
  12.                 success: function (data) {  
  13.                     // alert(data);  
  14.                     var series = new Array();  
  15.                     for (var i in data) {  
  16.                         var serie = new Array(data[i].Value, data[i].Item);  
  17.                         series.push(serie);  
  18.                     }  
  19.                     DrawPieChart(series);  
  20.                 },  
  21.                 error: function (xhr) {  
  22.                     alert('error');  
  23.                 }  
  24.             });  
  25.         });  
  26.         function DrawPieChart(series) {  
  27.             $('#container').highcharts({  
  28.   
  29.                 chart: {  
  30.                     plotBackgroundColor: null,  
  31.                     plotBorderWidth: 1, //null,  
  32.                     plotShadow: false  
  33.                 },  
  34.                 title: {  
  35.                     text: ' Vehicle Summary'  
  36.                 },  
  37.                 tooltip: {  
  38.                     pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'  
  39.                 },  
  40.                 plotOptions: {  
  41.                     pie: {  
  42.                         allowPointSelect: true,  
  43.                         cursor: 'pointer',  
  44.                         dataLabels: {  
  45.                             enabled: false  
  46.                         },  
  47.                         showInLegend: true  
  48.                     }  
  49.                 },  
  50.                 series: [{  
  51.                     type: 'pie',  
  52.                     name: 'Task Status',  
  53.                     data: series  
  54.                 }]  
  55.             });  
  56.         }  
  57. </script>  

Now add a div to show the chart:

  1. <div id="container" style="min-width: 350px; height: 350px; max-width: 600px; margin: 0 auto"></div>  
Now run the code. You will see the chart on page as in the following:



To use various types of charts like line, area column or bar chart, we need to specify the chart type and provide the formatted data to draw the chart.
  1. $('#container').highcharts({  
  2. chart: {  
  3. type: 'column'  
  4. },  
The required data format for each type of chart can be identified from the demo in jsfiddler of that chart.

Browse the demo URL and click on view options:

http://www.highcharts.com/demo/column-stacked 


Similar Articles