Click here to Skip to main content
Click here to Skip to main content

ASP.NET MVC Chart Control

By , 15 Nov 2010
 

Introduction

Chart control integration in ASP.NET MVC is very easy. Microsoft released a powerful Chart control in ASP.NET that supports a rich set of chart options - including column, spline, bar, point, bubble, pie, doughnut, pyramid, funnel, boxplot, area, range, AJAX interactive, and more. The Microsoft Chart Controls Sample Project includes over 200 chart samples for ASP.NET pages. In this post, I'm going to show how chart controls are used in ASP.NET MVC. My sample project is done in ASP.NET MVC 2.

Background

I introduce here a pretty simple project that shows the result comparison of a class. Two fields - ID (of a student which is unique) and GPA (Grade Point Average) - represent the result of a particular student. Various chart results show the comparison of results of students. I want to focus on how to easily show various results on the same data. In this project, you can add, edit, and delete student results and dynamically display the changes.

result-chart.png

cuid.gif

The Solution Overview

To run the project, the following components must be installed:

To get started, you will need to reference the System.Web.UI.DataVisualization assembly. Restore the database backup, or run the script located in the Database folder.

Once you have done this, it's pretty much simplicity itself to add a chart to a view page.

<img src="/Chart/CreateChart?chartType=
    <%=System.Web.UI.DataVisualization.Charting.SeriesChartType.Column%>" alt="" /> 

This calls the CreateChart action on the Chart controller with a parameter chartType. This parameter defines the type of your chart. SeriesChartType is an enumerator described in the System.Web.UI.DataVisualization.Charting namespace. This is a property of the Series class. The instance of the Series class will be added to the Chart class object. The action creates a chart in memory, saves the chart as an image to a temp folder, and then streams the image of the chart to the client. By the way, the action returns a FileResult.

This is the summary of the chart control. You will be more clear in the next section.

Using the Code

The controller code:
public FileResult CreateChart(SeriesChartType chartType)
{
      IList<ResultModel> peoples = _resultService.GetResults();
      Chart chart = new Chart();
      chart.Width = 700;
      chart.Height = 300;
      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(peoples,chartType));
      chart.ChartAreas.Add(CreateChartArea());

      MemoryStream ms = new MemoryStream();
      chart.SaveImage(ms);
      return File(ms.GetBuffer(), @"image/png");
}

The Chart class has various properties that can control the width, height, border color, background color, skin, palette, and so on. Title, legend, series, and chart area are very important characteristics for any chart. If you are not familiar with these terms, no worries. Take a quick look at the section Chart Elements Overview.

Creating the title:
public Title CreateTitle()
{
      Title title = new Title();
      title.Text = "Result Chart";
      title.ShadowColor = Color.FromArgb(32, 0, 0, 0);
      title.Font = new Font("Trebuchet MS", 14F, FontStyle.Bold);
      title.ShadowOffset = 3;
      title.ForeColor = Color.FromArgb(26, 59, 105);
      return title;
}

You will certainly understand that the title.Text property is responsible for representing a title. If you have multiple titles, add multiple times whatever you need.

Creating the legend:
public Title CreateTitle()
{
      Title title = new Title();
      title.Text = "Result Chart";
      title.ShadowColor = Color.FromArgb(32, 0, 0, 0);
      title.Font = new Font("Trebuchet MS", 14F, FontStyle.Bold);
      title.ShadowOffset = 3;
      title.ForeColor = Color.FromArgb(26, 59, 105);
      return title;
}

You can change the look and feel of the legend here. This is almost similar to the code for the title.

Creating a series:
public Series CreateSeries(IList<ResultModel> results, SeriesChartType chartType)
{
      Series seriesDetail = new Series();
      seriesDetail.Name = "Result Chart";
      seriesDetail.IsValueShownAsLabel = false;
      seriesDetail.Color = Color.FromArgb(198, 99, 99);
      seriesDetail.ChartType = chartType;
      seriesDetail.BorderWidth = 2;
      DataPoint point;

      foreach (ResultModel result in results)
      {
          point = new DataPoint();
          point.AxisLabel =result.ID;
          point.YValues = new double[] {double.Parse(result.GPA) };
          seriesDetail.Points.Add(point);
      }
      seriesDetail.ChartArea = "Result Chart";
      return seriesDetail;
}

Any chart element's x and y values are set as DataPoints. In this method, we get the values from the results collection. We add each value pair to the series Points collection. One thing is important here: a chart area may have multiple series, and we need to make sure which chart area contains which series.

You can set the various properties to change the look and feel.

Creating a chart area:
public ChartArea CreateChartArea()
{
      ChartArea chartArea = new ChartArea();
      chartArea.Name = "Result Chart";
      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;
}

You can control the various attributes of a chart area like the line color, label style, font, axis label interval, etc., from here. You can also enable the 3D style from here.

In short, a chart has multiple chart areas, and a chart area has multiple series, titles. A series has multiple legends. You can represent multiple chart series in the same chart area, or multiple chart areas in the same chart. The Name attribute is like ID, you can distinguish any property (chart area, series, or title) by this attribute.

Now you can make almost any chart based on your requirements. And you can change the look and feel by changing the appropriate styling attributes.

Chart Elements Overview

This portion I got from the Microsoft chart control samples. I included it here for better understanding the various elements of a chart.

A chart consists of numerous elements, all of which are accessible via the Chart control API. The Chart control API is object-oriented, extensible, and highly flexible.

The following figure illustrates the key elements that constitute a chart:

chart-area.JPG

The following list describes the major chart components:

  • Title: The main chart title. There can be an unlimited number of titles placed in a chart image. Note that a custom text can be displayed using GDI+ and the paint-related events.
  • Chart Area: The chart picture consists of one or more chart areas, which are rectangular areas that are used to draw series, labels, axes, grid lines, tick marks, and so on. Multiple series can be plotted in one chart area depending on the chart types involved.

    The plot area, used to plot chart data, is also contained within a chart area.

  • Chart Series: A series is a related group of data points. Each series is associated with a chart type.
  • Legend: A legend for the chart picture. There can be an unlimited number of legends in a chart.
  • Axis Label: A label along an axis.
  • Axis Title: The title of an axis.
  • Chart Picture: The chart picture is the entire image surface that is rendered by the Chart control. It corresponds to the root Chart object.
  • Grid Lines: There are major and minor horizontal and vertical grid lines, which usually occur in conjunction with tick marks.
  • Tick Marks: There are major and minor horizontal and vertical tick marks, which usually occur in conjunction with grid lines.
  • Plot Area: The plot area is the inner rectangular area within a chart area that is used to plot series and grid lines. Labels, tick marks, the axis title, and so on, are all drawn outside of the plotting area and inside the chart area. The plot area can be set via the ChartArea.InnerPlotPosition property.
  • Value Label: A special label that occurs for a data point, slightly offset from where the point is plotted. It can be the data point's value or custom text.

Additional Resources

Conclusion

The project presented here is just an example of how can you represent chart controls in ASP.NET MVC. You can improve it based on your requirements; this article gives you just the direction.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ariful Islam Sabuz
Software Developer Simplexhub
Bangladesh Bangladesh
Member
** I have been working in the information technology field, specializing in web development(mostly .NET), internet marketing, usability, and high profile website design.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questioncan u help me?memberK2@ketu22 May '13 - 2:22 
I am new to Telerik column chart.
I want to use Telerik Column chart to display employee Information from database.
and I dont know how to bound the data from database to the chart. i.e. its X-Axis and Y-Axis. can you please help me Confused | :confused:
 
Thanks in advance Smile | :)
GeneralMy vote of 5memberK2@ketu22 May '13 - 2:12 
Its nice and giving good knowledge Smile | :) Thumbs Up | :thumbsup:
GeneralMy vote of 5professionalPrasad Khandekar20 May '13 - 19:56 
Very nice!
GeneralMy vote of 5memberGregoryW21 Apr '13 - 19:54 
Gr8 article, i think i will use this kind of charts in my app.
GeneralMy vote of 5memberal13n20 Mar '13 - 14:03 
Easy to read and saved me lots of time. Thanks!
QuestionHow to change the interval Y axismemberdeepakaitr1234528 Oct '12 - 23:44 
Hi Arifu,
 
I have also implemented the grphs using your artical,
But one problem that i have is how can i chang the y axis interval
 
Please help me
 
Thanks
AnswerRe: How to change the interval Y axismemberSentenryu14 Jan '13 - 5:26 
For future reference:
chart.ChartAreas[0].AxisY.Interval
I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

QuestionShow the Y axis left and right with diffrent valuesmemberdeepakaitr1234521 Aug '12 - 2:36 
Hi Ariful,
 
The artical is very nice.
I have one queesction that is how can i put the values in Y axix but both are diffrent
like on left side y axis i need currency value and on the right side i want to show the percentage amount
 
How to do this
Please help me
 
Thanks
QuestionCreate Label wrongmemberMember 85519101 Jul '12 - 22:12 
I dont know if anyone told you, but you wrote
public Title CreateTitle()
when trying to give some information about how to create a legend.
I am not familiar with legends, but here is my try:
private Legend CreateLegend()
        {
            Legend legend = new Legend();
            legend.Enabled = true;
            legend.ShadowColor = Color.FromArgb(32, 0, 0, 0);
            legend.Font = new Font("Trebuchet MS", 14F, FontStyle.Bold);
            legend.ShadowOffset = 3;
            legend.ForeColor = Color.FromArgb(26, 59, 105);
            legend.Title = "Legend";
            return legend;
        }
 
Anyway, thanks for your tutorial, i saved it in my list of favorites!
SuggestionNice article!memberKunjan_Modi17 May '12 - 7:01 
I was wondering if you tried defining the Chart object using XML and simply deserialized it as runtime. This way:
 
1. We dont have to write so many methods to define a chart, &
2. No code changes would be needed if we have to update/enhance the chart definitions.
 
Also, have you tried this with MVC3?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 15 Nov 2010
Article Copyright 2010 by Ariful Islam Sabuz
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid