Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

ASP.NET MVC Chart Control

4.86/5 (59 votes)
15 Nov 2010CPOL5 min read 320.1K   17.4K  
Shows how chart controls are used in ASP.NET MVC

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.

ASP.NET
<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:
C#
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:
C#
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:
C#
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:
C#
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:
C#
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)