HTML5 has opened up so many cool possibilities, one of them being Chart.js. There have been times past in my career when I would have killed for something like this — well maybe not killed, but a savage beating would have been well warranted. I realise there are other charts out there, but I like these ones, and possibly more importantly, my current employer thinks I’m a genius since I released projects featuring them.
Anyway, let’s get on with it.
Implementing the chart is actually very straight forward, the challenge(?) is getting the data to populate it. So I’m going to take you through a couple of methods. First lets create a new web application
Next select MVC as the type.
Then we need to add Chart.js to the project. You can either do this by downloading it from Chart.js direct or using NuGet. I’m going to use NuGet. Go to the tools menu and select NuGet Package Manager then select Manage NuGet Packages for Solution. Once in there search for Chart.js
Next we need to add a reference in our project. Quite a few options for this too but really depends on how and where you are going to end up using charts. For the purposes of this demonstration I will use the BundleConfig.
There is some theory in the way that BundleConfig works that I would urge you to read up on, but I will not be going into here save to say that you need to add in a reference to the Chart.js.
Right, now to make some changes to the layout file. Firstly open up _Layout.cshtml and have a look at the contents. What we need to do here is take the @Script.Render line relating to jQuery and paste it at the top, just below the Moderniser one. Now below add one for Chart.js.
Ok, so I think we now have all the setup complete. Now we need to get the data in there.
For a model we are just going to use a basic Int array. Modify the Index method of the HomeController as follows.
Note: this is just one method, I will address others in part 2
Open up the Index view and delete all the existing HTML. Next we need to get the Int array we put in the ViewBag and create a string with each element separated by a comma.
var result = "@test"
var resultsArray = result.split(',');
More to follow in part 2