Tutorial on adding StockCharts into ASP.NET MVC Applications

This section contains tutorial on adding Interactive StockCharts into ASP.Net MVC (C#) Applications. CanvasJS StockChart includes components like Range Selector, Navigator, Slider, supports animation, printing entire StockChart, exporting StockChart as image (JPG / PNG) in client-side and performs 10x better compared to SVG / Flash based libraries – it can render Tens of Thousands of DataPoints in few milliseconds!

Below is a downloadable Visual Studio Project which you can download & run locally in order to understand the API better.

Download ASP.Net MVC StockChart Samples

Sample Solution runs on ASP.Net MVC5 & C#. But you can easily port it to any other versions as well. In case you don’t have Visual Studio, we recommend that you download it from here.

Step-By-Step Instruction

1. Create a Visual Studio Solution

As a first step, create an empty Visual Studio Project and add Home Controller & View as explained here. Name the project as “CanvasJS StockChart ASPNET MVC Samples”

2. Adding StockChart to View Page

Before creating the StockChart, you need to include CanvasJS StockChart Script in the header.

<script src="https://cdn.canvasjs.com/canvasjs.stock.min.js">

Once the script is added, you are ready to go. Create a div element inside the body and set its id as stockChartContainer. This is where the StockChart gets rendered.

<div id="stockChartContainer"></div>

Now add the following script just below the div or inside the head tag in the page. We are basically creating the StockChart inside window’s onload event.

<script type="text/javascript">
window.onload = function() {
var stockChart = new CanvasJS.StockChart("stockChartContainer", {
  title: {
    text: "CanvasJS StockChart in ASP.NET MVC"
  },
  charts: [{
    data: [{
      type: "line",
      dataPoints: [
        { x: new Date("2018-01-01"), y: 71 },
        { x: new Date("2018-02-01"), y: 55 },
        { x: new Date("2018-03-01"), y: 50 },
        { x: new Date("2018-04-01"), y: 65 },
        { x: new Date("2018-05-01"), y: 95 },
        { x: new Date("2018-06-01"), y: 68 },
        { x: new Date("2018-07-01"), y: 28 },
        { x: new Date("2018-08-01"), y: 34 },
        { x: new Date("2018-09-01"), y: 14 },
        { x: new Date("2018-10-01"), y: 71 },
        { x: new Date("2018-11-01"), y: 55 },
        { x: new Date("2018-12-01"), y: 50 },
        { x: new Date("2019-01-01"), y: 34 },
        { x: new Date("2019-02-01"), y: 50 },
        { x: new Date("2019-03-01"), y: 50 },
        { x: new Date("2019-04-01"), y: 95 },
        { x: new Date("2019-05-01"), y: 68 },
        { x: new Date("2019-06-01"), y: 28 },
        { x: new Date("2019-07-01"), y: 34 },
        { x: new Date("2019-08-01"), y: 65 },
        { x: new Date("2019-09-01"), y: 55 },
        { x: new Date("2019-10-01"), y: 71 },
        { x: new Date("2019-11-01"), y: 55 },
        { x: new Date("2019-12-01"), y: 50 }
      ]
    }]
  }],
  navigator: {
    slider: {
      minimum: new Date("2018-07-01"),
      maximum: new Date("2019-06-30")
    }
  }
});

stockChart.render();
}
</script>

3. Build and Run the solution to see the StockChart


4. Adding Dynamic Data

Above example has static data included inside the HTML page. But in most web applications you’ll require a StockChart from dynamic data. You can do this easily by passing dataPoints from the controller into the view as explained below.

In order to serialize the data we are using JSON.Net which you can install with following command by going to Tools -> NuGet Package Manager -> Package Manager Console.

PM> Install-Package Newtonsoft.Json

Also add System.Runtime.Serialization by going to Project -> Add References

Create Model

Now create a class named “DataPoint.cs” under Models folder by copy pasting the below code.

using System;
using System.Runtime.Serialization;

namespace CanvasJS_StockChart_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<double> X = null;

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

Update Controller

Once the DataPoint model is defined, you can create a list of Data Points in the controller and pass it on to the view.

using CanvasJS_StockChart_ASPNET_MVC_Samples.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace CanvasJS_StockChart_ASPNET_MVC_Samples.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            double count = 365, y = 100;
            double x = 1546281000000; // 1st Jan 2019 in timestamp (seconds);

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

            List<Models.DataPoint> dataPoints = new List<DataPoint>();

            for (int i = 0; i < count; i++)
            {
                y = Math.Abs(y + (random.Next(0, 20) - 10));
                x += 24 * 60 * 60 * 1000;
                dataPoints.Add(new DataPoint(x, y));
            }

            ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);
            
            return View();
        }
    }
}

Note that we are adding dataPoints inside controller using random number generator. You can replace the same with data coming from any other source like database, etc

Update View

Now set the ViewBag.DataPoints to dataPoints inside the view and you are done.

dataPoints: @Html.Raw(ViewBag.DataPoints)

Build and run the project to see the StockChart.

Refer to the StockChart Options section for complete list of options available. Also refer to Updating StockChart Options / Data section for tutorial on updating StockChart dynamically.



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