Tutorials & Samples on adding Charts into ASP.NET MVC Applications

This section contains tutorial & samples on adding Interactive HTML5 Charts into ASP.Net MVC (C#) Applications. CanvasJS comes with 30 types of Responsive Charts and 10x better performance compared to SVG / Flash based charting libraries – it can render Tens of Thousands of DataPoints in few milliseconds! In this section we’ll be explaining on how to add various chart types and features into ASP.Net & MVC Applications

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

Download ASP.Net MVC Chart Samples    Checkout Demo Gallery

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 “ASPNET MVC Samples”

2. Adding Chart to View Page

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

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

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

<div id="chartContainer"></div>

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

<script type="text/javascript">

	window.onload = function () {
		var chart = new CanvasJS.Chart("chartContainer", {
			theme: "light2",
			animationEnabled: true,
			title: {
				text: "Simple Column Chart in ASP.NET MVC"
			},
			subtitles: [
				{ text: "Try Resizing the Browser" }
			],
			data: [
			{
				type: "column", //change type to bar, line, area, pie, etc
				dataPoints: [
				{ x: 10, y: 71 },
				{ x: 20, y: 55 },
				{ x: 30, y: 50 },
				{ x: 40, y: 65 },
				{ x: 50, y: 95 },
				{ x: 60, y: 68 },
				{ x: 70, y: 28 },
				{ x: 80, y: 34 },
				{ x: 90, y: 14 }
				]
			}
			]
		});
		chart.render();
	};
</script>

3. Build and Run the solution to see the chart


4. Adding Dynamic Data

Above example has static data included inside the HTML page. But in most web applications you’ll require a chart 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.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<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 ASPNET_MVC_Samples.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ASP.Net_CanvasJS_Tutorial.Controllers
{
	public class HomeController : Controller
	{
		// GET: Home
		public ActionResult Index()
		{
			List<DataPoint> dataPoints = new List<DataPoint>{
				new DataPoint(10, 22),
				new DataPoint(20, 36),
				new DataPoint(30, 42),
				new DataPoint(40, 51),
				new DataPoint(50, 46),
			};

			ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);

			return View();
		}


	}
}

Note that we are adding dataPoints inside controller manually. 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 an run the project to see the chart.

Tip

You can change the Chart Type by changing “type” property in view to “line”, “area”, “spline”, “bar”, “pie”, etc.


@{
	Layout = null;
}

<!DOCTYPE html>

<html>
<head>
	<meta name="viewport" content="width=device-width" />
	<script src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
	<title>Index</title>
</head>
<body>
	<div id="chartContainer"></div>

	<script type="text/javascript">

		window.onload = function () {
			var chart = new CanvasJS.Chart("chartContainer", {
				theme: "light2",
				animationEnabled: true,
				title: {
					text: "Simple Column Chart in ASP.NET MVC"
				},
				subtitles: [
					{ text: "Try Resizing the Browser" }
				],
				data: [
				{
					type: "column", //change type to bar, line, area, pie, etc
					dataPoints: [
					{ x: 10, y: 71 },
					{ x: 20, y: 55 },
					{ x: 30, y: 50 },
					{ x: 40, y: 65 },
					{ x: 50, y: 95 },
					{ x: 60, y: 68 },
					{ x: 70, y: 28 },
					{ x: 80, y: 34 },
					{ x: 90, y: 14 }
					]
                                        //Uncomment below line to add data coming from the controller.
					//dataPoints: @Html.Raw(ViewBag.DataPoints),
				}
				]
			});
			chart.render();
		};
	</script>

</body>
</html>
using ASPNET_MVC_Samples.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ASP.Net_CanvasJS_Tutorial.Controllers
{
	public class HomeController : Controller
	{
		// GET: Home
		public ActionResult Index()
		{
			List<DataPoint> dataPoints = new List<DataPoint>{
				new DataPoint(10, 22),
				new DataPoint(20, 36),
				new DataPoint(30, 42),
				new DataPoint(40, 51),
				new DataPoint(50, 46),
			};

			ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);

			return View();
		}


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

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

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