This lesson goes over the steps needed to build a chart bound to data in Visual Studio using a series template.
To create a chart, do the following.
Result
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….
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.
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;
}
}
}
Public Class Gdp
Private mProduct As Double
Private mYear As Integer
Private mCountry As String
Public ReadOnly Property Country() As String
Get
Return mCountry
End Get
End Property
Public ReadOnly Property Year() As Integer
Get
Return mYear
End Get
End Property
Public ReadOnly Property Product() As Double
Get
Return mProduct
End Get
End Property
Public Sub New(country As String, year As Integer, product As Double)
mCountry = country
mYear = year
mProduct = product
End Sub
End Class
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;
}
}
}
Imports System.Collections.ObjectModel
Public Class GdpProvider
Dim mFilepath As String
Sub New(filepath As String)
mFilepath = filepath
End Sub
Function GetGdps() As IEnumerable(Of Gdp)
Dim gdps = New Collection(Of Gdp)
Dim document = XDocument.Load(mFilepath)
Dim root As XElement = document.Element("G7GDPs")
For Each elementGdp As XElement 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)))
Next
Return gdps
End Function
End Class
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 19.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());
}
}
}
Public Class ChartController
Inherits System.Web.Mvc.Controller
Function Index() As ActionResult
Return View(New GdpProvider(Server.MapPath("~/App_Data/GDPofG7.xml")).GetGdps())
End Function
End Class
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()
@Code
ViewBag.Title = "Getting Started Lesson 3"
End Code
@Html.DevExpress().Chart(Sub(settings)
' Specify the obligatory chart name.
settings.Name = "chart"
End Sub)
.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"));
// ...
' ...
settings.Name = "chart"
' Configure a template used to generate series.
settings.Series.Template(Sub(t)
t.SetDataMembers("Year", "Product")
End Sub)
' ...
The chart is created. If you run the application now, it will look as follows.
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;
// ...
' ...
Name = "chart"
' Modify the chart appearance.
PaletteName = "Office 2013"
Width = 1280
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);
});
// ...
' ...
settings.Series.Template(Sub(t)
t.SetDataMembers("Year", "Product");
t.Views().LineSeriesView(Sub(v) v.MarkerVisibility = DefaultBoolean.True)
End Sub);
' ...
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");
// ...
' ...
settings.PaletteName = "Office 2013"
' Add a chart title.
settings.Titles.Add(Sub(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";
});
// ...
' ...
' Configure the diagram after series because diagram can be changed
' to be compatible with the series view type.
settings.XYDiagram(Sub(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"
End Sub)
' ...
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;
// ...
' ...
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 Legend.AlignmentHorizontal and Legend.AlignmentVertical properties) and align legend items from left to right (using the Legend.Direction property).
// ...
// Customize the default legend.
settings.Legends.Default(l => {
l.AlignmentHorizontal = LegendAlignmentHorizontal.Left;
l.AlignmentVertical = LegendAlignmentVertical.Top;
l.Direction = LegendDirection.LeftToRight;
});
// ...
' ...
' Customize the default legend.
settings.Legends.Default(Sub(l)
l.AlignmentHorizontal = LegendAlignmentHorizontal.Left
l.AlignmentVertical = LegendAlignmentVertical.Top
l.Direction = LegendDirection.LeftToRight
End Sub);
' ...
Result
The application is done and its source code should look like as follows.
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;
}
}
}
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());
}
}
}
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;
}
}
}
@model IEnumerable<GettingStarted3.Models.Gdp>
@{
ViewBag.Title = "Getting Started Lesson 3";
}
@Html.DevExpress().Chart(settings => {
// Specify the obligatory chart name.
settings.Name = "Chart";
settings.Width = 640;
settings.Height = 360;
settings.PaletteName = "Office 2013";
// Configure a template used to generate series.
settings.Series.Template(t => {
t.SetDataMembers("Year", "Product");
t.Views().LineSeriesView(v => {
v.MarkerVisibility = DefaultBoolean.True;
});
});
// Add a chart title.
settings.Titles.Add(t => t.Text = "G7 GDP");
// 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";
// Configure scale options to show only integer value tickmarks.
d.AxisX.NumericScaleOptions.MeasureUnit = NumericMeasureUnit.Ones;
d.AxisX.NumericScaleOptions.GridOffset = 1;
// Set the Y-axis title text and show it.
d.AxisY.Title.Visibility = DefaultBoolean.True;
d.AxisY.Title.Text = "GDP, billions of USD";
});
settings.Legends.Default(l => {
l.AlignmentHorizontal = LegendAlignmentHorizontal.Left;
l.AlignmentVertical = LegendAlignmentVertical.Top;
l.Direction = LegendDirection.LeftToRight;
});
}).Bind(Model, "Country").GetHtml()
Public Class Gdp
Private mProduct As Double
Private mYear As Integer
Private mCountry As String
Public ReadOnly Property Country() As String
Get
Return mCountry
End Get
End Property
Public ReadOnly Property Year() As Integer
Get
Return mYear
End Get
End Property
Public ReadOnly Property Product() As Double
Get
Return mProduct
End Get
End Property
Public Sub New(country As String, year As Integer, product As Double)
mCountry = country
mYear = year
mProduct = product
End Sub
End Class
@Code
ViewBag.Title = "Getting Started Lesson 3"
End Code
@Html.DevExpress().Chart(Sub(settings)
' Specify the obligatory chart name.
settings.Name = "Chart"
settings.Width = 640
settings.Height = 360
settings.PaletteName = "Office 2013"
' Configure a template used to generate series.
settings.Series.Template(Sub(t)
t.SetDataMembers("Year", "Product")
t.Views().LineSeriesView(Sub(v) v.MarkerVisibility = DefaultBoolean.True)
End Sub)
' Add a chart title.
settings.Titles.Add(Sub(t) t.Text = "G7 GDP")
' Configure the diagram after series because diagram can be changed
' to be compatible with the series view type.
settings.XYDiagram(Sub(d)
' Set the X-axis title text And show it.
d.AxisX.Title.Visibility = DefaultBoolean.True
d.AxisX.Title.Text = "Year"
' Configure scale options to show only integer value tickmarks.
d.AxisX.NumericScaleOptions.MeasureUnit = NumericMeasureUnit.Ones
d.AxisX.NumericScaleOptions.GridOffset = 1
' Set the Y-axis title text And show it.
d.AxisY.Title.Visibility = DefaultBoolean.True
d.AxisY.Title.Text = "GDP, billions of USD"
End Sub)
settings.Legends.Default(Sub(l)
l.AlignmentHorizontal = LegendAlignmentHorizontal.Left
l.AlignmentVertical = LegendAlignmentVertical.Top
l.Direction = LegendDirection.LeftToRight
End Sub)
End Sub).Bind(Model, "Country").GetHtml()
Imports System.Collections.ObjectModel
Public Class GdpProvider
Dim mFilepath As String
Sub New(filepath As String)
mFilepath = filepath
End Sub
Function GetGdps() As IEnumerable(Of Gdp)
Dim gdps = New Collection(Of Gdp)
Dim document = XDocument.Load(mFilepath)
Dim root As XElement = document.Element("G7GDPs")
For Each elementGdp As XElement 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)))
Next
Return gdps
End Function
End Class
Public Class ChartController
Inherits System.Web.Mvc.Controller
Function Index() As ActionResult
Return View(New GdpProvider(Server.MapPath("~/App_Data/GDPofG7.xml")).GetGdps())
End Function
End Class
Run the application. The following image demonstrates its appearance.