Saturday, 26 September 2015

Creating a Flot Chart with jQuery Flot and ASP.NET Web API 2

Step 1 : Create ASP.NET Web API 2 project

Step 2: Create Master_Site and SiteAnalyticsData Models in Model Folder

Master_Site


SiteAnalyticsData
Step 3: Add Context Class in Model Folder

Step 4: Open Package Manager Console Enable MIgration and Add Migration then Update database in 
PM> enable-migrations
PM> add-migration "Initial"
PM> update-database

Step 5 : Go to database and add some dummy data like 

Now our data is ready.

Step 6: Create a Web api Controller and paste the below code

using jQueryFlotChart.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace jQueryFlotChart.Controllers
{
    public class ChartController : ApiController
    {
        public dynamic Get(int year)
        {
            using (SampleDbContext context = new SampleDbContext())
            {

                var alldata = (from item in context.SiteAnalyticsDatas
                               where item.Date.Year == year && item.SiteID == 1
                               group item by item.Date.Month into grp
                               select new
                               {
                                   Month = grp.Key,
                                   Visitors = grp.Sum(x => x.Visitors),
                                   Visits = grp.Sum(x => x.Visits),
                                   PageViews = grp.Sum(x => x.PageViews)
                               }).ToList();

         var ret = new[]
        {  
            new { label="PageViews", data = alldata.Select(x=>new int[]{ x.Month, x.PageViews })},
            new { label="Visits", data = alldata.Select(x=>new int[]{ x.Month, x.Visits })},
            new { label="Visitors", data = alldata.Select(x=>new int[]{ x.Month, x.Visitors })}
            
        };

         return ret;
            }
        }

    }
}
Step 7 : Go to manage package Manager and search for flot and instal it... or you can directly download from Flot website and keep the required js and css file. 
one css file we have to take from flot website... when you will download the file in that example.css will be there so you can use that.


Step 8: Go to View : Home> Index and write /Paste the following code                              

@{Layout = null;}

<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="~/Scripts/flot/excanvas.min.js"></script><![endif]-->
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/flot/jquery.flot.min.js"></script>

<script type="text/javascript">
    $(function () {
        debugger;
        var dataurl = 'api/Chart/';
        $.ajax({
            url: dataurl,
            method: 'GET',
            data: { year: 2012 },
            dataType: 'json',
            success: function (data) {
                debugger;

                $.plot($("#placeholder"), data, options);
            }
        });
        // setup plot
        var options = {
            legend: {
                show: true,
                margin: 10,
                backgroundOpacity: 0.9
            },
            points: {
                show: true,
                radius: 3
            },
            lines: {
                show: true
            },
            grid: { hoverable: true, clickable: true },
            yaxis: { min: 0, tickFormatter: formatter },
            xaxis: { ticks: [[1, "Jan"], [2, "Feb"], [3, "Mar"], [4, "Apr"], [5, "May"], [6, "Jun"], [7, "Jul"], [8, "Aug"], [9, "Sep"], [10, "Oct"], [11, "Nov"], [12, "Dec"]] }

        };
        function formatter(val, axis) {
            return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }
       
    });



    var previousPoint = null;
    $("#placeholder").bind("plothover", function (event, pos, item) {
        if (item) {
            if (previousPoint != item.dataIndex) {
                previousPoint = item.dataIndex;

                $("#tooltip").remove();
                var x = item.datapoint[0],
                    y = item.datapoint[1].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                showTooltip(item.pageX, item.pageY, item.series.label + ": " + y);

            }
        }
        else {
            $("#tooltip").remove();
            previousPoint = null;
        }
    });


    function showTooltip(x, y, contents) {
        $('<div id="tooltip">' + contents + '</div>').css({
            position: 'absolute',
            display: 'none',
            top: y + 5,
            left: x + 5,
            border: '1px solid #fdd',
            padding: '2px',
            'background-color': '#fee',
            opacity: 0.80
        }).appendTo("body").fadeIn(200);
    }

</script>




<section style="width: 500px; margin: 10px; text-align:center;">
    <div id="placeholder" style="width: 500px; height: 300px;">
    </div>
    <h3 style="font-size:1.4em">Traffic Overview - 2015 </h3>
</section>

Done: RUN the application you will get the o/p.




2 comments: