Feb 10

Display data in chart using ASP.NET MVC

1.    Introduction

Chart is also called as graph and it is graphical representation of data. The data is represented in the form of bar in bar chart, line in line chart and slices using pie chart. Chart can usually be read more quickly than the row data. Chart is the greatest and simplest way to express data to user or management persons. Charts are very common in all type of business requirement. If you want to develop dashboard then charting is absolutely necessary for your users especially for management.
Today, I came across the situation in my current ongoing assignment where graphical dashboard is required. So I did Google for it and come across different approaches to implement it. Last two three days I explored different approaches by making smaller proof of concepts. In today’s post I am going to explain how we can create the chart using Chart Helper provided my Microsoft ASP.NET MVC.

2.    Overview

In my careers starting days with ASP.NET, I remember we used different type of third party control to implement chart functionality in applications. But now using Microsoft ASP.NET MVC provides inbuilt support for Chart in a very simpler fashion. The “System.Web.Helpers” namespace used to implement the chart functionality.
2.1   Chart Helper:
Using chart helper you can create chart images of different types with many formatting options and labels. It can be used to create area chart, bar chart, column chart, line chart and pie charts along with more specialized types of charts like stock charts. The chart helper can render more than 30 types of chats. The data you display in chart can be in the form of array, for database or using data in the file.
2.2   Chart Elements:
The chart shows the actual data and additional elements like axis, legends, series, axis title, chat title and plotting area. The following picture shows the chart elements that you  can customize as per your need using chart helper.
 

2.3   Chart types:

The chart control defines different type of charts. Each chart defines unique set of requirements based on features. ASP.NET MVC Chart Helper provides below type of charts. SeriesChartType enumeration defines below charts.
Chart Type
Description
Bar Chart
Illustrates comparisons among individual items.
Column Chart
Uses a sequence of columns to compare values across categories.
Doughnut Chart
Similar to the Pie chart type, except that it has a hole in the center.
Line Chart
Illustrates trends in data with the passing of time.
Pie Chart
Shows how proportions of data, shown as pie-shaped pieces, contribute to the data as a whole.
I haven’t tried all of them but only required to my project assignment, hence given description to used specific only. You can find complete set of types by clicking here
2.4   Styling:
The chart helper support number of option to customize it’s look and feel. You can set color, fonts, border etc. The “theme” is used to customize the charts look and feel. The themes are collection of information the specifies the rendering option using fonts, color, label, palettes, and effects. The following table shows in build option supported in chart helper.
Theme Name
Description
Vanilla
Displays red columns on a white background.
Blue
Displays blue columns on a blue gradient background.
Green
Displays blue columns on a green gradient background.
Yellow
Displays orange columns on a yellow gradient background.
Vanilla3D
Displays 3-D red columns on a white background.
2.5   Methods or Functions:
Below are the functions and properties used to set while using chart helper.
Function
Description
new Chart()
It creates a new chart object and sets its width and height
AddTitle()
This method adds the tile to the chart
AddLegend()
Adds the legend to the chart
Addseries()
It is used for providing data points and series of attributes for the chart.
SetXAxis()
It sets the value for the horizontal axis (X-Axis).
SetYAxis()
It sets the value for the vertical  axis (Y-Axis).
Save()
By using this method we can save the chart image to the specified file.
SaveToCache()
It saves the chart image in the system cache.
Write()
The method displays the chart.
DataBindTable()
This method binds the data source to the chart
chartType
This parameter defines the type of chart
xValue
This parameter defines x-axis names
yValues
This parameter defines the y-axis values
2.6   Saving:
The charts recreates the chart from scratch every time you loads the page. If you do the complex operation using database or LINQ query like grouping  then it may hamper performance of your website page. So to avoid or reduce this you can create chart at first time and save it and whenever required fetch the saved version and render it. Below are the options you can save the chart.
1. Cache the chart on server memory
2. Save chart as image on server
3. Save chat as xml file
2.7   Caching
Once you create chart you can save it. So no need of recreate it. You can clear cache on demand also or it automatically clear whenever your application restarts.

3.    Practical Implementation

There are multiple ways to achieve charting functionality. You can create chart using arrays, database query or using xml data. Below example explains how to create chart using arrays.
Step 1:
Create a MVC razor page(Index.cshtml) and add below code in it. This action will display the Bar chart.
<table>
    <tr>
        <th colspan=”2″ style=”height:100px; text-align:center”><b>GDP Dashboard of top Countries</b></th>
    </tr>
    <tr>
        <td rowspan=”2″>
            <img src=”@Url.Action(“CreateCountryGDPBar”) />
        </td>
    </tr>
</table>
Step 2:
Create Controller with default Index action and give implementation of CreateCountryGDPBar acton as below code sample. TO run this example you need to import System.Web.Helpers namespace In your controller.
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult CreateCountryGDPBar()
        {
            var chart = new System.Web.Helpers.Chart(width: 300, height: 200, theme: ChartTheme.Blue)
             .AddTitle(“GDP Current Prices in Billion($)”)
            .AddSeries(
                    chartType: “column”,
                    name: “StudyType”,
                    xValue: new[] { “USA”, “China”, “Japan”, “Germany”, “UK”, “France”, “India” },
                        yValues: new[] { “17968”, “11385”, “4116”, “3371”, “2865”, “2423”, “2183” })
             .GetBytes(“png”);
            return File(chart, “image/bytes”);
        }
Step 3:
This will display the bar chart
 
This code is very self-explanatory. You just need to set height, width and default skin in Chart constructor. Give the title to display on top of chart. xValues and yValues are the properties to display actual data, chartType is used to display the type of data  and  use GetByte method to return image in png format. Return the file as return data of action and in output you will see the chart as above.
Below sample describes the how to display another bar and pie charts using different themes.
Place below code into your view and controller.
        <td>
            <img src=”@Url.Action(“ComparisonBar”)“/>
        </td>
        public ActionResult ComparisonBar()
        {
            var chart = new System.Web.Helpers.Chart(width: 500, height: 300)
            .AddTitle(“GDP Ranking (USDA) in Billions($)”)
            .AddSeries(
                chartType: “column”,
                xValue: new[] { “USA”, “China”, “Japan”, “Germany”, “France”, “UK”, “India” },
                yValues: new[] { 16656, 8774, 5704, 3668, 2762, 2637, 2366 },
                name: “2015”)
            .AddSeries(
                chartType: “column”,
                xValue: new[] { “USA”, “China”, “Japan”, “Germany”, “France”, “UK”, “India” },
                yValues: new[] { 23857, 18829, 6535, 4308, 3476, 3815, 7269 },
                name: “2030”)
            .AddLegend()
            .GetBytes(“png”);
            return File(chart, “image/bytes”);
        }
This will display below bar chart result.
        <td>
            <img src=”@Url.Action(“CreateCountryGDPPie”)“/>
        </td>
        public ActionResult CreateCountryGDPPie()
        {
            var chart = new System.Web.Helpers.Chart(width: 300, height: 200, theme: ChartTheme.Vanilla)
            .AddTitle(“GDP Current Prices in Billion($)”)
            .AddLegend()
            .AddSeries(chartType: “pie”,
                        xValue: new[] { “USA”, “China”, “Japan”, “Germany”, “UK”, “France”, “India”},
                        yValues: new[] { “17968”, “11385”, “4116”, “3371”, “2865”, “2423”, “2183” })
            .GetBytes(“png”);
            return File(chart, “image/bytes”);
        }
This will display below pie chart result.
 
 
Suppose you want to customize your chat the you need to add customize code for that. Below example shows hot to customize bar chart using C# code. To customize cod you need to import using System.Web.UI.DataVisualization.Charting namespace in your application.Add below code sample in your view and controller
        <td rowspan=”2″>
            <img src=”@Url.Action(“CreateGDPRankingBar”) />
        </td>
  public class StatusNumber
  {
        public string Status { get; set; }
        public string Number { get; set; }
  }
        public ActionResult CreateGDPRankingBar()
        {
            var statusNumbers = new List<StatusNumber>
            {
                new StatusNumber{Number=“17968”, Status=“USA”},
                new StatusNumber{Number=“11385”, Status=“China”},
                new StatusNumber{Number=“4116”, Status=“Japan”},
                new StatusNumber{Number=“3371”, Status=“Germany”},
                new StatusNumber{Number=“2865”, Status=“UK”},
                new StatusNumber{Number=“2423”, Status=“France”},
                new StatusNumber{Number=“2183”, Status=“India”},
            };
            var chart = new System.Web.UI.DataVisualization.Charting.Chart();
            chart.Width = 350;
            chart.Height = 400;
            chart.BackColor = Color.FromArgb(211, 223, 240);
            chart.BorderlineDashStyle = ChartDashStyle.Solid;
            chart.BackSecondaryColor = Color.White;
            chart.BackGradientStyle = GradientStyle.TopBottom;
            chart.BorderlineWidth = 1;
            chart.Palette = ChartColorPalette.BrightPastel;
            chart.BorderlineColor = Color.FromArgb(26, 59, 105);
            chart.RenderType = RenderType.BinaryStreaming;
            chart.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
            chart.AntiAliasing = AntiAliasingStyles.All;
            chart.TextAntiAliasingQuality = TextAntiAliasingQuality.Normal;
            chart.Titles.Add(CreateTitle());
            chart.Legends.Add(CreateLegend());
            chart.Series.Add(CreateSeries(SeriesChartType.Bar, statusNumbers));
            chart.ChartAreas.Add(CreateChartArea());
            MemoryStream ms = new MemoryStream();
            chart.SaveImage(ms);
            return File(ms.GetBuffer(), @”image/png”);
        }
       
        public Title CreateTitle()
        {
            Title title = new Title
            {
                Text = “GDP Current Prices in Billion($)”,
                ShadowColor = Color.FromArgb(32, 0, 0, 0),
                Font = new Font(“Trebuchet MS”, 14F, FontStyle.Bold),
                ShadowOffset = 3,
                ForeColor = Color.FromArgb(26, 59, 105)
            };
            return title;
        }
        public Series CreateSeries(SeriesChartType chartType, ICollection<StatusNumber> list)
        {
            var series = new Series
            {
                Name = “GDP Current Prices in Billion($)”,
                IsValueShownAsLabel = true,
                Color = Color.FromArgb(198, 99, 99),
                ChartType = chartType,
                BorderWidth = 2
            };
            foreach (var item in list)
            {
                var point = new DataPoint
                {
                    AxisLabel = item.Status,
                    YValues = new double[] { double.Parse(item.Number) }
                };
                series.Points.Add(point);
            }
            return series;
        }
        public ChartArea CreateChartArea()
        {
            var chartArea = new ChartArea();
            chartArea.Name = “GDP Current Prices in Billion($)”;
            chartArea.BackColor = Color.Transparent;
            chartArea.AxisX.IsLabelAutoFit = false;
            chartArea.AxisY.IsLabelAutoFit = false;
            chartArea.AxisX.LabelStyle.Font = new Font(“Verdana,Arial,Helvetica,sans-serif”, 8F, FontStyle.Regular);
            chartArea.AxisY.LabelStyle.Font = new Font(“Verdana,Arial,Helvetica,sans-serif”, 8F, FontStyle.Regular);
            chartArea.AxisY.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea.AxisX.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea.AxisY.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea.AxisX.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea.AxisX.Interval = 1;
            return chartArea;
        }
        public Legend CreateLegend()
        {
            var legend = new Legend
            {
                Name = “GDP Current Prices in Billion($)”,
                Docking = Docking.Bottom,
                Alignment = StringAlignment.Center,
                BackColor = Color.Transparent,
                Font = new Font(new FontFamily(“Trebuchet MS”), 9),
                LegendStyle = LegendStyle.Row
            };
            return legend;
        }
This will display bar chart as below
If you integrate all above action methods and view code it will display chart as below.

I hope you enjoyed the sample code that I provided. I would suggest you to play something around the code and theme.

4.    Other Chart Available

4.1   High Chart
4.2   Chart.js
4.3   Kendo Charts
4.4   Component Art
4.5   Infragistic Chart

5.    Summary

Using MVC Chart helper, it is very easy to show chart in your ASP.NET MVC application. In this article, I showed  you how to create a chart in ASP.NET MVC. I also showed you how to style a chart and how to change the background color of a chart. Hopefully you will enjoy this article too.  In my next blog post article I will explain how Chart.js and Highcharts JavaScript library are useful to display charts in advanced fashion.

2 comments

1 ping

  1. very usefull for me .this article should solve my problems in chart helper so i shall try it……………

  2. This article helped to create charts in few hours ,but looking how to make the background lines disappear in charts?

    • Anonymous on April 15, 2018 at 7:18 AM

    Wonderful content. With thanks!

Leave a Reply