Working with data in ASP.NET CORE Chart Component

20 Jun 202424 minutes to read

Chart can visualize data bound from local or remote data.

Local data

You can bind a simple JSON data to the chart using dataSource property in series. Now, map the fields in JSON to xName and yName properties.

<ejs-chart id="container" title="Inflation - Consumer Price" width="60%">
        <e-chart-primaryxaxis valueType="DateTime"
                              labelFormat="y"
                              intervalType="Years"
                              edgeLabelPlacement="Shift"></e-chart-primaryxaxis>
        <e-series-collection>
            <e-series dataSource="ViewBag.dataSource" name="Germany" xName="xValue" width="2" opacity="1" yName="yValue" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Line"></e-series>
        </e-series-collection>
    </ejs-chart>
public IActionResult Index()
        {
           List<LineData> chartData = new List<LineData>
            {
                new LineData { xValue = new DateTime(2005, 01, 01), yValue = 21, yValue1 = 28 },
                new LineData { xValue = new DateTime(2006, 01, 01), yValue = 24, yValue1 = 44 },
                new LineData { xValue = new DateTime(2007, 01, 01), yValue = 36, yValue1 = 48 },
                new LineData { xValue = new DateTime(2008, 01, 01), yValue = 38, yValue1 = 50 },
                new LineData { xValue = new DateTime(2009, 01, 01), yValue = 54, yValue1 = 66 },
                new LineData { xValue = new DateTime(2010, 01, 01), yValue = 57, yValue1 = 78 },
                new LineData { xValue = new DateTime(2011, 01, 01), yValue = 70, yValue1 = 84 },
            };
            ViewBag.dataSource = chartData;
            return View();
        }
        public class LineData
        {
            public DateTime xValue;
            public double yValue;
            public double yValue1;
        }

Common datasource

You can also bind a JSON data common to all series using dataSource property in chart.

<ejs-chart id="container">
    <e-chart-primaryxaxis valueType="Category"></e-chart-primaryxaxis>
    <e-series-collection>
        <e-series dataSource="ViewBag.dataSource" xName="month" yName="sales" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Column">
        </e-series>
        <e-series dataSource="ViewBag.dataSource" xName="month" yName="sales" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Column">
        </e-series>
    </e-series-collection>
</ejs-chart>
public ActionResult Index()
        {
            List<GroupingChartData> chartData = new List<GroupingChartData>
            {

                new GroupingChartData {  month= "Jan", sales= 35, sales1= 28 },
                new GroupingChartData { month= "Feb", sales= 28, sales1= 35 },
                new GroupingChartData { month= "Mar", sales= 34, sales1= 32 },
                new GroupingChartData { month= "Apr", sales= 32, sales1= 34 },
                new GroupingChartData { month= "May", sales= 40, sales1= 32  },
                new GroupingChartData { month= "Jun", sales= 32, sales1= 40  },
                new GroupingChartData { month= "Jul", sales= 35, sales1= 55  },
                new GroupingChartData { month= "Aug", sales= 55, sales1= 35 },
                new GroupingChartData { month= "Sep", sales= 38, sales1= 30 },
                new GroupingChartData { month= "Oct", sales= 30, sales1= 38  },
                new GroupingChartData { month= "Nov", sales= 25, sales1= 32 },
                new GroupingChartData { month= "Dec", sales= 32, sales1= 25 }

            };
            ViewBag.dataSource = chartData;
            return View();
        }
        public class GroupingChartData
        {
            public string month;
            public double sales;
            public double sales1;
        }

Remote data

You can also bind remote data to the chart using DataManager. The DataManager requires minimal information like webservice URL, adaptor and crossDomain to interact with service endpoint properly. Assign the instance of DataManager to the dataSource property in series and map the fields of data to xName and yName properties. You can also use the query property of the series to filter the data.

<ejs-chart id="lineContainer">

        <e-chart-primaryxaxis title="Assignee" rangePadding="Additional" valueType="Category"></e-chart-primaryxaxis>
        <e-series-collection>
            <e-series name="Story Point" xName="CustomerID" width=2 yName="Freight" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Column" query="new ej.data.Query().take(5).where('Estimate', 'lessThan', 3, false)">
                <e-data-manager url='https://services.syncfusion.com/aspnet/production/api/orders' crossdomain="true"></e-data-manager>
                <e-series-marker>
                    <e-series-datalabel visible="true" position="Top"></e-series-datalabel>
                </e-series-marker>
                <e-series-animation enable="false"></e-series-animation>
            </e-series>
        </e-series-collection>
    </ejs-chart>
public ActionResult Index()
        {

            return View();
            
        }

Binding data using ODataAdaptor

OData is a standardized protocol for creating and consuming data. You can retrieve data from an OData service using the DataManager. Refer to the following code example for remote data binding using an OData service.

<ejs-chart id="container" title="Order Details">
    <e-chart-primaryxaxis valueType="@Syncfusion.EJ2.Charts.ValueType.Category"></e-chart-primaryxaxis>
    <e-series-collection>
        <e-series xName="CustomerID" yName="Freight" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Column" query="new ej.data.Query()">
            <e-data-manager url="https://services.odata.org/V3/Northwind/Northwind.svc/Orders/" adaptor="ODataAdaptor" crossdomain="true"></e-data-manager>
        </e-series>
    </e-series-collection>
</ejs-chart>
public ActionResult Index()
{
    return View();
}

Binding data using ODataV4Adaptor

ODataV4 is an improved version of the OData protocols, and the DataManager can also retrieve and consume ODataV4 services. For more details on ODataV4 services, refer to the odata documentation. To bind an ODataV4 service, use the ODataV4Adaptor.

<ejs-chart id="container" title="Order Details">
    <e-chart-primaryxaxis valueType="@Syncfusion.EJ2.Charts.ValueType.Category"></e-chart-primaryxaxis>
    <e-series-collection>
        <e-series xName="CustomerID" yName="Freight" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Column" query="new ej.data.Query()">
            <e-data-manager url="https://services.odata.org/V4/Northwind/Northwind.svc/Orders" adaptor="ODataV4Adaptor"></e-data-manager>
        </e-series>
    </e-series-collection>
</ejs-chart>
public ActionResult Index()
{
    return View();
}

Web API adaptor

You can use the WebApiAdaptor to bind the chart with a Web API created using an OData endpoint.

<ejs-chart id="container" title="Order Details">
    <e-chart-primaryxaxis valueType="@Syncfusion.EJ2.Charts.ValueType.Category"></e-chart-primaryxaxis>
    <e-series-collection>
        <e-series xName="CustomerID" yName="Freight" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Column" query="new ej.data.Query()">
            <e-data-manager url="https://services.syncfusion.com/aspnet/production/api/orders" adaptor="WebApiAdaptor"></e-data-manager>
        </e-series>
    </e-series-collection>
</ejs-chart>
public ActionResult Index()
{
    return View();
}

The response object should contain the properties Items and Count, where Items represents a collection of entities, and Count represents the total number of entities.

The sample response object should appear as follows:

{
    Items: [{..}, {..}, {..}, ...],
    Count: 830
}

Custom adaptor

You can create your own adaptor by extending the built-in adaptors. The following demonstrates the custom adaptor approach and how to add a serial number to the records by overriding the built-in response processing using the processResponse method of the ODataAdaptor.

<ejs-chart id="container" title="Order Details" load="load">
    <e-chart-primaryxaxis valueType="@Syncfusion.EJ2.Charts.ValueType.Category"></e-chart-primaryxaxis>
    <e-series-collection>
        <e-series xName="CustomerID" yName="Sno" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Column" query="query">
        </e-series>
    </e-series-collection>
</ejs-chart>

<script>
    class SerialNoAdaptor extends ej.data.ODataAdaptor {
        processResponse() {
            var i= 0;
            // calling base class processResponse function
            var original = super.processResponse.apply(this, arguments);
            // adding serial number
            original.result.forEach(function(item){item['Sno'] = ++i});
            return { result: original.result, count: original.count };
        }
    }
    var dataManager = new ej.data.DataManager({
        url: 'https://services.syncfusion.com/aspnet/production/api/orders',
        adaptor: new SerialNoAdaptor()
    });
    var query = new ej.data.Query();
    function load(args) {   
        args.chart.series[0].dataSource = dataManager;
    }
</script>
public ActionResult Index()
{
    return View();
}

Offline mode

When using remote data binding, all chart actions will be processed on the server-side. To avoid postback for every action, configure the chart to load all data upon initialization and handle actions on the client-side. To enable this behavior, utilize the offline property of the DataManager.

<ejs-chart id="container" title="Order Details">
    <e-chart-primaryxaxis valueType="@Syncfusion.EJ2.Charts.ValueType.Category"></e-chart-primaryxaxis>
    <e-series-collection>
        <e-series xName="CustomerID" yName="Freight" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Column" query="new ej.data.Query()">
            <e-data-manager url="https://services.syncfusion.com/aspnet/production/api/orders" adaptor="ODataAdaptor" offline="true"></e-data-manager>
        </e-series>
    </e-series-collection>
</ejs-chart>
public ActionResult Index()
{
    return View();
}

Empty points

The Data points that uses the null or undefined as value are considered as empty points. Empty data points are ignored and not plotted in the Chart. When the data is provided by using the points property, by using emptyPointSettings property in series, you can customize the empty point. Default mode of the empty point is Gap.

<ejs-chart id="container" title="Inflation - Consumer Price" width="60%">
        <e-chart-primaryxaxis valueType="Category"></e-chart-primaryxaxis>
        <e-series-collection>
            <e-series dataSource="ViewBag.dataSource" name="Germany" xName="month" width="2" opacity="1" yName="sales" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Column">
                <e-series-emptypointsettings mode="@Syncfusion.EJ2.Charts.EmptyPointMode.Gap"></e-series-emptypointsettings>
            </e-series>
        </e-series-collection>
    </ejs-chart>
public IActionResult Index()
        {
            List<EmptyData> chartData = new List<EmptyData>
            {
               new EmptyData{ month="Jan", sales= 35 },
               new EmptyData{ month= "Feb", sales= 28 },
               new EmptyData{ month="Mar", sales=null },
               new EmptyData{ month="Apr", sales=32 },
               new EmptyData{ month="May", sales=40 },
               new EmptyData{ month= "Jun", sales=32 },
               new EmptyData{ month="Jul", sales=35 },
               new EmptyData{ month="Aug", sales=null },
               new EmptyData{ month="Sep", sales=38 },
               new EmptyData{ month="Oct", sales=30 },
               new EmptyData{ month="Nov", sales=25 },
               new EmptyData{ month= "Dec", sales=32 }
            };
            ViewBag.dataSource = chartData;
            return View();
        }
        public class EmptyData
        {
            public string month;
            public Nullable<double> sales;
        }

Lazy loading

Lazy loading allows to load data for chart on demand. Chart will fire the scrollEnd event, in that the minimum and maximum range of the axis is achieved. Based on this, the data can be uploaded to chart.

<ejs-chart id="container" load="window.onChartLoad" scrollEnd="scrollEnd">
            <e-chart-chartarea>
                <e-chartarea-border width="0"></e-chartarea-border>
            </e-chart-chartarea>
            <e-chart-primaryxaxis edgeLabelPlacement="Shift" title="Day" valueType="DateTime" skeleton="yMMM" skeletonType="Date">
                <e-scrollbarSettings enable="true" pointsLength="1000"></e-scrollbarSettings>
                <e-majorgridlines width="0"></e-majorgridlines>
            </e-chart-primaryxaxis>
            <e-chart-primaryyaxis interval="10" title="Server Load" labelFormat="{value}MB">
                <e-majorticklines width="0"></e-majorticklines>
                <e-linestyle width="0"></e-linestyle>
            </e-chart-primaryyaxis>
            <e-series-collection>
                <e-series xName="x" yName="y" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Line">
                    <e-series-animation enable="false"></e-series-animation>
                </e-series>
            </e-series-collection>
            <e-chart-tooltipsettings enable="true" shared="true"></e-chart-tooltipsettings>
            <e-chart-legendsettings visible="false"></e-chart-legendsettings>
            <e-chart-legendsettings visible="false"></e-chart-legendsettings>
        </ejs-chart>

        <script>
              var intl = new ej.base.Internationalization();
        var chart;
            function scrollEnd(args) {
            if (modeType.value === 'Range') {
                chart.series[0].dataSource = GetDateTimeData(args.currentRange.minimum, args.currentRange.maximum);
            } 
            chart.dataBind();

        }
        </script>

        window.onChartLoad = function (args) {
            args.chart.series[0].dataSource = GetDateTimeData(new Date(2009, 0, 1), new Date(2009, 8, 1)),
            args.chart.primaryXAxis.scrollbarSettings.range = { minimum: new Date(2009, 0, 1), maximum: new Date(2014, 0, 1) }

        }
           function GetDateTimeData(start, end) {
            var series1 = [];
            var date;
            var value = 30;
            var option = { skeleton: 'full', type: 'dateTime' };

            var dateParser = intl.getDateParser(option);
            var dateFormatter = intl.getDateFormat(option);
            for (var i = 0; start <= end; i++) {
                date = Date.parse(dateParser(dateFormatter(start)));
                if (Math.random() > .5) {
                    value += (Math.random() * 10 - 5);
                } else {
                    value -= (Math.random() * 10 - 5);
                }
                if (value < 0) {
                    value = getRandomInt(20, 40);
                }
                var point1 = { x: new Date(date), y: Math.round(value) };
                new Date(start.setDate(start.getDate() + 1));
                series1.push(point1);
            }
            return series1;
        }
       function getRandomInt(min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
public IActionResult Index()
        {
            ViewBag.min = new DateTime(2009, 1, 1);
            ViewBag.max = new DateTime(2014, 1, 1);
            return View();
        }

Customizing empty point

Specific color for empty point can be set by fill property in emptyPointSettings. Border for a empty point can be set by border property.

<ejs-chart id="container" title="Inflation - Consumer Price" width="60%">
        <e-chart-primaryxaxis valueType="Category"></e-chart-primaryxaxis>
        <e-series-collection>
            <e-series dataSource="ViewBag.dataSource" name="Germany" xName="month" width="2" opacity="1" yName="sales" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Column">
                <e-series-emptypointsettings fill="#e6e6e6" mode="@Syncfusion.EJ2.Charts.EmptyPointMode.Average"></e-series-emptypointsettings>
            </e-series>
        </e-series-collection>
    </ejs-chart>
public IActionResult Index()
        {
            List<EmptyData> chartData = new List<EmptyData>
            {
               new EmptyData{ month="Jan", sales= 35 },
               new EmptyData{ month= "Feb", sales= 28 },
               new EmptyData{ month="Mar", sales=null },
               new EmptyData{ month="Apr", sales=32 },
               new EmptyData{ month="May", sales=40 },
               new EmptyData{ month= "Jun", sales=32 },
               new EmptyData{ month="Jul", sales=35 },
               new EmptyData{ month="Aug", sales=null },
               new EmptyData{ month="Sep", sales=38 },
               new EmptyData{ month="Oct", sales=30 },
               new EmptyData{ month="Nov", sales=25 },
               new EmptyData{ month= "Dec", sales=32 }
            };
            ViewBag.dataSource = chartData;
            return View();
        }
        public class EmptyData
        {
            public string month;
            public Nullable<double> sales;
        }