Skip to main content

Lesson 3 - Create a Chart Using a Series Template

  • 8 minutes to read

This lesson goes over the steps needed to build a chart bound to data in Visual Studio using a series template.

Step 1. Create a New Project

In this step, do the following preparatory work.

  • Create a new ASP.NET MVC project integrated with DevExpress ASP.NET MVC Extensions.
  • Add a new empty ChartController to the project.
  • Add a new empty Chart | Index View to the project.

To learn how to do this, refer to Lesson 1.

Now the blank project is ready for further customization.

Step 2. Add a Data Model

In this step, a data model used to provide data to the View will be added to the project.

  • In the Solution Explorer, right-click the Models folder. In the invoked menu, click Add | New Item….

    Lesson3_AddNewItemMenu

  • In the invoked Add New Item dialog, select the Class group and then select the Class item. Set the Class name to Gdp and click Add.

    Lesson3_AddNewItem

    Add the following code to the newly created class.

    namespace GettingStarted3.Models {
        public class Gdp {
            public string Country { get; private set; }
            public int Year { get; private set; }
            public double Product { get; private set; }
    
            public Gdp(string country, int year, double product) {
                this.Country = country;
                this.Year = year;
                this.Product = product;
            }
        }
    }
    
  • Then, create a new GdpProvider class as was done in the previous steps and add the following code to it.

    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Xml.Linq;
    
    namespace GettingStarted3.Models {
        public class GdpProvider {
            string filepath;
    
            public GdpProvider(string filepath) {
                this.filepath = filepath;
            }
    
            public IEnumerable<Gdp> GetGdps() {
                Collection<Gdp> gdps = new Collection<Gdp>();
                XDocument document = XDocument.Load(filepath);
                XElement root = document.Element("G7GDPs");
                foreach(XElement elementGdp in root.Elements("GDP")) {
                    gdps.Add(new Gdp(
                        country: elementGdp.Element("Country").Value,
                        year: Convert.ToInt32(elementGdp.Element("Year").Value),
                        product: Convert.ToDouble(elementGdp.Element("Product").Value)));
                }
                return gdps;
            }
        }
    }
    
  • Find the GDPofG7.xml file shipped with the DevExpress DemoCenter and copy it to the App_Data directory within the project directory.

    Note

    By default, the file is located in the C:\Users\Public\Documents\DevExpress Demos 24.1\Components\ASP.NET\CS\MVCxChartDemos\App_Data folder.

  • Add the following code to the ChartController class definition.

    using GettingStarted3.Models;
    using System.Web.Mvc;
    
    namespace GettingStarted3.Controllers {
        public class ChartController : Controller {
            public ActionResult Index() {
                return View(new GdpProvider(Server.MapPath("~/App_Data/GDPofG7.xml")).GetGdps());
            }
        }
    }
    

    In this code, a collection of GDP values is loaded from the file copied from the DemoCenter. Then, the collection is assigned to the Model property of the Chart | Index View using the View’s constructor, which takes a model object as an argument.

Now, the Model preparation is finished and data can be provided to a Chart.

Step 3. Create a Chart

In this step, a Chart is added to the View and the series bound to the Model is added to the Chart.

  • Create a new ChartControlExtension. Bind the View.Model property to it and specify the series data member using the ChartControlExtension.Bind method (series data member values will be used to identify series). Finally, obtain the resulting HTML code using the ExtensionBase.GetHtml method. The following code snippet demonstrates how to do this.

    @{
        ViewBag.Title = "Getting Started Lesson 3";
    }
    
    @Html.DevExpress().Chart(settings => {
        // Specify the obligatory chart name.
        settings.Name = "chart";
    }).Bind(Model, "Country").GetHtml()
    
  • Specify the SeriesBase.ArgumentDataMember and SeriesBase.ValueDataMembers properties of a series template to bind automatically generated series arguments and values to the Model properties. To obtain the series template, use the XtraChartsCollectionExtensions.Template method. Then, to specify the properties, use the SeriesBase.SetDataMembers method.

    // ...
    settings.Name = "chart";
    
    // Configure a template used to generate series.
    settings.Series.Template(t => t.SetDataMembers("Year", "Product"));
    // ...
    

The chart is created. If you run the application now, it will look as follows.

Lesson3_Step3_Result

Required data is provided to the Chart. In the next step, let’s customize the chart appearance.

Step 4. Customize the Chart

In this step, the appearance of chart and series is improved and the chart title and axis titles are added.

  • To change the default palette, specify the ChartControlSettings.PaletteName property value. Also, to adjust the chart size, change its ChartControlSettings.Width and ChartControlSettings.Height properties.

    // ...
    settings.Name = "chart";
    
    // Modify the chart appearance.
    settings.PaletteName = "Office 2013";
    settings.Width = 1280;
    settings.Height = 720;
    // ...
    
  • To customize the view of all automatically generated series, use the XtraChartsSeriesBaseExtensions.Views method. Change the series view to line using the SeriesViewActionMethodContainer.LineSeriesView method of an object returned by Views(). For example, show markers by setting the LineSeriesView.MarkerVisibility property value of the view to DefaultBoolean.True.

    // ...
    settings.Series.Template(t => {
        t.SetDataMembers("Year", "Product");
        t.Views().LineSeriesView(v => v.MarkerVisibility = DefaultBoolean.True);
    });
    // ...
    
  • To add a chart title, use the XtraChartsCollectionExtensions.Add method, which will allow you to configure an added ChartTitle object. Specify the title’s Title.Text property as shown below.

    // ...
    settings.PaletteName = "Office 2013";
    
    // Add a chart title.
    settings.Titles.Add(t => t.Text = "G7 GDP");
    // ...
    
  • To specify an axis title, call the ChartControlSettings.XYDiagram method allowing you to configure the chart’s diagram as a diagram of the XYDiagram type. Then, using the XYDiagram.AxisY property, get access to the Y-axis settings and assign the Millions of USD string value to the Title.Text property of Axis.Title. Finally, set TitleBase.Visible to DefaultBoolean.True to show the Y-axis title.

    Repeat these actions to show the “Year” title for the X-axis.

    // ...
    // Configure the diagram after series because diagram can be changed
    // to be compatible with the series view type.
    settings.XYDiagram(d => {
        // Set the X-axis title text and show it.
        d.AxisX.Title.Visibility = DefaultBoolean.True;
        d.AxisX.Title.Text = "Year";
    
        // Set the Y-axis title text and show it.
        d.AxisY.Title.Visibility = DefaultBoolean.True;
        d.AxisY.Title.Text = "GDP, billions of USD";
    });
    // ...
    
  • To configure for which numeric values axis labels should be displayed, obtain the NumericScaleOptions object using the AxisBase.NumericScaleOptions property and modify it. For example, to show labels for each integer value, set the NumericScaleOptions.MeasureUnit property value to Ones and ScaleGridOptionsBase.GridOffset to 1.

    // ...
    d.AxisY.Title.Text = "GDP, billions of USD";
    
    // Configure scale options to show only integer value tickmarks.
    d.AxisX.NumericScaleOptions.MeasureUnit = NumericMeasureUnit.Ones;
    d.AxisX.NumericScaleOptions.GridOffset = 1;
    // ...
    
  • To change the default legend options, use the XtraChartsCollectionExtensions.Default method. In this lesson, this method is used to locate the legend at the top-left corner of the chart (using the LegendBase.AlignmentHorizontal and LegendBase.AlignmentVertical properties) and align legend items from left to right (using the LegendBase.Direction property).

    // ...
    // Customize the default legend.
    settings.Legends.Default(l => {
        l.AlignmentHorizontal = LegendAlignmentHorizontal.Left;
        l.AlignmentVertical = LegendAlignmentVertical.Top;
        l.Direction = LegendDirection.LeftToRight;
    });
    // ...
    

Result

Lesson3_Result