Click here to Skip to main content
12,890,181 members (44,540 online)
Click here to Skip to main content
Add your own
alternative version

Stats

13.4K views
769 downloads
6 bookmarked
Posted 3 Sep 2014

Passing JSON Data to a CanvaJS Chart in ASP.NET MVC

, 3 Sep 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This tip is aimed at helping anyone who encounters a similar problem like I had in displaying charts using ASP MVC and dynamic data.

Introduction

This tip shows how you can use an SQL Server database to display dynamic charts in your application. basically I show you how to convert data into JSON and pass it to view from a controller to display charts. Most examples on the internet show tutorials using static data which can be difficult for beginners like myself when we need to do a real application. I hope that it can help someone out there who may face a similar situation.

Background

To illustrate the concept, I created a dummy application that displays defect/incidents in projects during different phases and environments. I used Entity Framework Database first concept and LINQ to entities/SQL.

Using the Code

Firstly I have four tables in SQL server: Defect, Project, Environment and Incident. You will see the schema in the accompanying source code.

I have a Dashboard controller that looks like this. Notice how you convert data to JSON in code highlighted in bold.

    public class DashboardController : Controller
    {   
        // GET: /Dashboard/
       public ActionResult Index()
        {
            return View();
        }
        public ContentResult GetData()
        {
            using (var db = new QualityMatricsEntities1())
            {
                var result = (from tags in db.Defects
                              orderby tags.DefectDate ascending
                              select new { tags.Description, tags.NumberOfDefects }).ToList();
                //return Json(JsonConvert.SerializeObject(result), JsonRequestBehavior.AllowGet);
                return Content(JsonConvert.SerializeObject(result), "application/json");
            }
        }
        public ContentResult GetDefect()
        {
            using (var db = new QualityMatricsEntities1())
            {

                var defect = (from d in db.Defects
                              join e in db.Environments on d.DefectID equals e.EnvID
                              select new
                              {
                                  d.Description,
                                  d.NumberOfDefects,
                                  e.EnvName
                              }).ToList();

                return Content(JsonConvert.SerializeObject(defect));
          }
}
}

Now, I am going to the view (Index.cshtml in this case). My code looks like this: I also notice the code highlighted in bold which shows you how to pass json in the $.getJson line and how to push data points to a Canvas chart.

@model IEnumerable<ChartDemo.Models.Project>

@{
    ViewBag.Title = "Index";
}

<!--Load the AJAX API-->

<script type="text/javascript" src="~/Scripts/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/jquery-2.1.1.min.js"></script>

<script type="text/html" src="~/Scripts/canvasjs.min.js"></script>
<script src="~/Scripts/canvasjs.js"></script>
<script src="~/Scripts/excanvas.js"></script>


<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<script type="text/javascript">
    $(document).ready(function () {
        var dataPoints = [];
        $.getJSON("/Dashboard/GetData/", function (data) {
            for (var i = 0; i <= data.length -1; i++) {
                dataPoints.push({ label: data[i].Description, y: parseInt(data[i].NumberOfDefects) });
            }
            var chart = new CanvasJS.Chart("chartContainer", {
                theme: "theme2",//theme1
                title: {
                    text: "Defects"
                },
                data: [
                {
                    // Change type to "bar", "splineArea", "area", "spline", "pie",etc.
                    type: "column",
                    dataPoints: dataPoints
                }
                ]
            });

            chart.render();
        });
    });
</script>

<body>
    <div id="chartContainer" style="height: 300px; width: 50%; float:right"></div>

</body>

<script type="text/javascript">
    $(document).ready(function () {
        var dataPoints = [];
        $.getJSON("/Dashboard/GetDefect/", function (data) {
            for (var i = 0; i <= data.length - 1; i++) {
                dataPoints.push({ label: data[i].EnvName, y: parseInt(data[i].NumberOfDefects) });
            }
            var chart = new CanvasJS.Chart("chartContainer1", {
                theme: "theme2",//theme1
                title: {
                    text: "Number of Defects by Environment"
                },
                data: [
                {
                    // Change type to "bar", "splineArea", 
                    "area", "spline", "pie",etc.
                    type: "line",
                    dataPoints: dataPoints
                }
                ]
            });

            chart.render();
        });

    });
</script>

<body>
    <div id="chartContainer1" style="height: 300px; width: 50%;"></div>

</body> 

<body>
    <div id="chartContainer2" style="height: 300px; width: 50%; float:right"></div>

</body>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Xavi Giqwa
Software Developer (Junior)
South Africa South Africa
I am a junior developer, currently developing my skill-set in application development. my interests include BI, C#, ASP MVC, SQL, JavaScript and learning C++ for developing games in .Net

You may also be interested in...

Pro

Comments and Discussions

 
GeneralMy vote of 1 Pin
Member 1130316117-Dec-14 19:49
memberMember 1130316117-Dec-14 19:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170424.1 | Last Updated 3 Sep 2014
Article Copyright 2014 by Xavi Giqwa
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid