HomedocschartsintegrationASP.NET MVChow to samplesUpdating Live Chart from external JSON

Updating Charts from JSON Data API in ASP.NET MVC Application

Here is an example on Updating Chart using JSON Data API in ASP.NET MVC Application. Generally it’s a good idea to fetch data via ajax rather than embedding in the web page. JSON data is easy to parse and generate the chart accordingly.

If you haven’t already, please refer to this tutorial for step by step instruction of adding charts to your ASP.Net MVC Application. We recommend that you download the Sample Visual Studio Project and try it on your own to understand the API better.


Download ASP.Net MVC Chart Samples

We will be using following JSON format in this example:

[
  {"x":0.0,"y":11.0},
  {"x":1.0,"y":17.0},
  {"x":2.0,"y":8.0},
  {"x":3.0,"y":15.0},
  {"x":4.0,"y":19.0},
  {"x":5.0,"y":19.0},
  {"x":6.0,"y":24.0},
  {"x":7.0,"y":19.0},
  .
  .
  .
]

Here are the steps:

Step 1:

We will update the controller to generate and serve the randomly generated dataPoints based on the number of dataPoints (count) and starting value of x (xStart).

using ASPNET_MVC_Samples.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ASPNET_MVC_Samples.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        public ContentResult JSON(double count = 50, double xStart = 0)
        {
            double y = 10;

            Random random = new Random(DateTime.Now.Millisecond);

            List<DataPoint> dataPoints;

            dataPoints = new List<DataPoint>();

            for (int i = 0; i < count; i++)
            {
                y = y + (random.Next(0, 20) - 10);

                dataPoints.Add(new DataPoint(xStart++, y));
            }

            JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() 
            { 
                    NullValueHandling = NullValueHandling.Ignore 
            };

            return Content(JsonConvert.SerializeObject(dataPoints, _jsonSetting), "application/json");
        }

    }
}

Step 2:

We will create a basic chart using JSON Data. We will get and parse the JSON Data using jQuery and convert the data to CanvasJS supported format if not already formatted (Please refer to Working with Data). Then we will initialize a chart and pass the dataPoints to the chart. In this example, JSON Data is already formatted according to CanvasJS, please refer to JavaScript Charts Using JSON & AJAX for example with different JSON format.

var dataPoints = [], chart;

// initial chart
$.get("/home/json?count=10", function (data) {
	dataPoints = data;

	chart = new CanvasJS.Chart("chartContainer", {
		animationEnabled: true,
		theme: "light2",//light1
		title: {
			text: "CanvasJS Charts in ASP.Net MVC using JSON & AJAX"
		},
		data: [
		  {
			// Change type to "bar", "splineArea", "area", "spline", "pie",etc.
			type: "line",
			dataPoints: dataPoints
		  }
		]
	});

	chart.render();

});

Step 3:

Now we will add a method updateChart to update the chart with new dataPoint. Each time updateChart is called, it gets data from JSON, adds it to dataPoints and calls chart.render()

function updateChart() {
	$.getJSON("/home/json?count=1&xStart="+ (dataPoints.length + 1) , function (data) {
		$.each(data, function (index) {
			dataPoints.push(data[index]);
		});
		chart.render();
		setTimeout(function () { updateChart() }, 1000);
	});
}

Finalising

To summarize, in order to create a Live Chart using JSON Data, we just need to fetch and parse the data to CanvasJS supported format and then pass the dataPoints to the chart whenever we want to update the chart.


@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
    <script src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
</head>
<body>
    <h1>Live / Dynamic Chart using JSON & AJAX</h1>
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>

    <script type="text/javascript">
    $(document).ready(function () {
        var dataPoints = [], chart;

        // initial chart
        $.get("/home/json?count=10", function (data) {
            dataPoints = data;

            chart = new CanvasJS.Chart("chartContainer", {
                animationEnabled: true,
                theme: "light2",//light1
                title: {
                    text: "CanvasJS Live Charts in ASP.Net MVC using JSON & AJAX"
                },
                data: [
                  {
                    // Change type to "bar", "splineArea", "area", "spline", "pie",etc.
                    type: "line",
                    dataPoints: dataPoints
                  }
                ]
            });

            chart.render();
            setTimeout(function () { updateChart() }, 1000);
        });
    
        function updateChart() {
            $.getJSON("/home/json?count=1&xStart="+ (dataPoints.length + 1) , function (data) {
                $.each(data, function (index) {
                    dataPoints.push(data[index]);
                });
                chart.render();
                setTimeout(function () { updateChart() }, 1000);
            });
        }
    
    });
    </script>
</body>
</html>			
using ASPNET_MVC_Samples.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ASPNET_MVC_Samples.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        public ContentResult JSON(double count = 50, double xStart = 0)
        {
            double y = 10;

            Random random = new Random(DateTime.Now.Millisecond);

            List dataPoints;

            dataPoints = new List();

            for (int i = 0; i < count; i++)
            {
                y = y + (random.Next(0, 20) - 10);

                dataPoints.Add(new DataPoint(xStart++, y));
            }

            JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };

            return Content(JsonConvert.SerializeObject(dataPoints, _jsonSetting), "application/json");
        }

    }
}			
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;

namespace ASPNET_MVC_Samples.Models
{
    //DataContract for Serializing Data - required to serve in JSON format
    [DataContract]
    public class DataPoint
    {
        public DataPoint(double x, double y)
        {
            this.X = x;
            this.Y = y;
        }

        //Explicitly setting the name to be used while serializing to JSON.
        [DataMember(Name = "x")]
        public Nullable X = null;

        //Explicitly setting the name to be used while serializing to JSON.
        [DataMember(Name = "y")]
        public Nullable Y = null;
    }
}			


If you have any questions, please feel free to ask in our forums.Ask Question