Tuesday, September 3, 2013

Bar Charts and Graphs in Asp.net mvc

Hi friends,

Yesterday i came across a scenario where i needed to display mt data in pictorial format to user for readability, i was searhing some jquery plugin to achieve that so that i can make graphs and bar charts in my application and i found many plugins but the one i found best for me was http://www.highcharts.com/

it has alot of data representation controls available, i used one of this.

Here is the way how you can build a bar chart ot graph:



For making chart or graph first we have to add these lines in  the view:



<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>

now add a div in view which will contain the chart, it will be our container :


<div id="myDiv" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

Now you add this code in your view, for understanding there is static data here passed but you can get data via ajax or get in action and on view use it in this function:

 

<script type="text/javascript">
                      var chart1;
                      $(document).ready(function () {
                          chart1 = new Highcharts.Chart({
                              chart: {
                                  type: 'spline',
                                  renderTo: 'myDiv'
                              },
                              title: {
                                  text: 'Monthly Tests Processed',
                                  x: -20 //center
                              },
                              subtitle: {
                                  text: '2013',
                                  x: -20
                              },
                              xAxis: {
                                  categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                              },
                              yAxis: {
                                  title: {
                                      text: 'No. of test processed'
                                  },
                                  plotLines: [{
                                      value: 0,
                                      width: 1,
                                      color: '#808080'
                                  }]
                              },
                              tooltip: {
                                  valueSuffix: 'Tests Processed'
                              },
                              legend: {
                                  layout: 'vertical',
                                  align: 'right',
                                  verticalAlign: 'middle',
                                  borderWidth: 0
                              },
                              series: [{
                                  name: '2013',
                                  data: [10, 20, 8, 40, 21, 90, 60, 44, 0, 35, 16,41]
                              }]
                          });
                      });
    

  </script>

but in the below view you will see i am filling data dynamically by getting from server side that will make you better understand.

Controller Action

Here is my controller code:


public class DashboardController : Controller
    {
        //
        // GET: /Dashboard/

        public ActionResult Index()
        {

            if (Session["user"] != null)
            {

                Session["ViewFlag"] = "Dashboard";

                DashboardViewModel objDashboardViewModel = new DashboardViewModel();



                return View(objDashboardViewModel.GetVerifiedTests((long)Session["userID"]));
            }

            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        

    }

View Model 

Here is my view model code:


public class DashboardViewModel
    {
        public int YearCount { get; set; }
        public int TodayCount { get; set; }
        public int TodayOverdueCount { get; set; }
        public int TodayOnTimeCount { get; set; }
        public int JanuaryCount { get; set; }
        public int FabruaryCount { get; set; }
        public int MarchCount { get; set; }
        public int AprilCount { get; set; }
        public int MayCount { get; set; }
        public int JuneCount { get; set; }
        public int JulyCount { get; set; }
        public int AugustCount { get; set; }
        public int SeptemberCount { get; set; }
        public int OctoberCount { get; set; }
        public int NovemeberCount { get; set; }
        public int DecemberCount { get; set; }

        public DashboardViewModel GetEnteredTests(long PersonID)
        {

            DashboardViewModel objDashboardViewModel = new DashboardViewModel();

            using (var db = new bc_limsEntities())
            {
                var result = (from r in db.dc_tresult

                              join tr in db.dc_tstatustrack on r.bookingdid equals tr.bookingdid

                              where tr.processid == 5

                                 && tr.enteredby == PersonID

                              select new { r.bookingdid, r.enteredon }).Distinct();

                //XmlDocument doc = new XmlDocument();

                //XmlElement root = doc.CreateElement("Performance");

                //doc.AppendChild(root);

                //int month = 0;

                //XmlElement child = doc.CreateElement("January");
                //root.AppendChild(child);
                //child = doc.CreateElement("February");
                //root.AppendChild(child);
                //child = doc.CreateElement("March");
                //root.AppendChild(child);
                //child = doc.CreateElement("April");
                //root.AppendChild(child);
                //child = doc.CreateElement("May");
                //root.AppendChild(child);
                //child = doc.CreateElement("June");
                //root.AppendChild(child);
                //child = doc.CreateElement("July");
                //root.AppendChild(child);
                //child = doc.CreateElement("August");
                //root.AppendChild(child);
                //child = doc.CreateElement("September");
                //root.AppendChild(child);
                //child = doc.CreateElement("October");
                //root.AppendChild(child);
                //child = doc.CreateElement("November");
                //root.AppendChild(child);
                //child = doc.CreateElement("December");
                //root.AppendChild(child);

                //XmlElement count = doc.CreateElement("Total");
                //count.InnerText = result.Count().ToString();

                //root.AppendChild(count);
                int totalCounter = 0;
                int todayCounter = 0;
                int janCounter = 0;
                int febCounter = 0;
                int marCounter = 0;
                int aprCounter = 0;
                int mayCounter = 0;
                int junCounter = 0;
                int julCounter = 0;
                int augCounter = 0;
                int sepCounter = 0;
                int octCounter = 0;
                int novCounter = 0;
                int decCounter = 0;

                //XmlElement todayCount = doc.CreateElement("Today");

                //root.AppendChild(todayCount);

                foreach (var item in result)
                {
                    if(item.enteredon.Month == 1 && item.enteredon.Year == DateTime.Now.Year)
                    {
                        janCounter ++;
                        //XmlNode janNode = doc.SelectSingleNode("//January");
                        //XmlElement january = doc.CreateElement(item.bookingdid.ToString());
                        //janNode.AppendChild(january);
                    }
                    if (item.enteredon.Month == 2 && item.enteredon.Year == DateTime.Now.Year)
                    {
                        febCounter++;
                        //XmlNode febNode = doc.SelectSingleNode("//February");
                        //XmlElement february = doc.CreateElement(item.bookingdid.ToString());
                        //febNode.AppendChild(february);
                    }
                    if (item.enteredon.Month == 3 && item.enteredon.Year == DateTime.Now.Year)
                    {
                        marCounter++;
                        //XmlNode marNode = doc.SelectSingleNode("//March");
                        //XmlElement march = doc.CreateElement(item.bookingdid.ToString());
                        //marNode.AppendChild(march);
                    }
                    if (item.enteredon.Month == 4 && item.enteredon.Year == DateTime.Now.Year)
                    {
                        aprCounter++;
                        //XmlNode aprNode = doc.SelectSingleNode("//April");
                        //XmlElement april = doc.CreateElement(item.bookingdid.ToString());
                        //aprNode.AppendChild(april);
                    }
                    if (item.enteredon.Month == 5 && item.enteredon.Year == DateTime.Now.Year)
                    {
                        mayCounter++;
                        //XmlNode mayNode = doc.SelectSingleNode("//May");
                        //XmlElement may = doc.CreateElement(item.bookingdid.ToString());
                        //mayNode.AppendChild(may);
                    }
                    if (item.enteredon.Month == 6 && item.enteredon.Year == DateTime.Now.Year)
                    {
                        junCounter++;
                        //XmlNode junNode = doc.SelectSingleNode("//June");
                        //XmlElement june = doc.CreateElement(item.bookingdid.ToString());
                        //junNode.AppendChild(june);
                    }
                    if (item.enteredon.Month == 7 && item.enteredon.Year == DateTime.Now.Year)
                    {
                        julCounter++;
                        //XmlNode julNode = doc.SelectSingleNode("//July");
                        //XmlElement july = doc.CreateElement(item.bookingdid.ToString());
                        //julNode.AppendChild(july);
                    }
                    if (item.enteredon.Month == 8 && item.enteredon.Year == DateTime.Now.Year)
                    {
                        augCounter++;
                        //XmlNode augNode = doc.SelectSingleNode("//August");
                        //XmlElement august = doc.CreateElement(item.bookingdid.ToString());
                        //augNode.AppendChild(august);
                    }
                    if (item.enteredon.Month == 9 && item.enteredon.Year == DateTime.Now.Year)
                    {
                        sepCounter++;
                        //XmlNode sepNode = doc.SelectSingleNode("//September");
                        //XmlElement september = doc.CreateElement(item.bookingdid.ToString());
                        //sepNode.AppendChild(september);
                    }
                    if (item.enteredon.Month == 10 && item.enteredon.Year == DateTime.Now.Year)
                    {
                        octCounter++;
                        //XmlNode octNode = doc.SelectSingleNode("//October");
                        //XmlElement october = doc.CreateElement(item.bookingdid.ToString());
                        //octNode.AppendChild(october);
                    }
                    if (item.enteredon.Month == 11 && item.enteredon.Year == DateTime.Now.Year)
                    {
                        novCounter++;
                        //XmlNode novNode = doc.SelectSingleNode("//November");
                        //XmlElement november = doc.CreateElement(item.bookingdid.ToString());
                        //novNode.AppendChild(november);
                    }
                    if (item.enteredon.Month == 12 && item.enteredon.Year == DateTime.Now.Year)
                    {
                        decCounter++;
                        //XmlNode decNode = doc.SelectSingleNode("//December");
                        //XmlElement december = doc.CreateElement(item.bookingdid.ToString());
                        //decNode.AppendChild(december);
                    }

                        if (item.enteredon == DateTime.Now)
                        {

                            todayCounter++;

                        }

                        if (item.enteredon.Year == DateTime.Now.Year)
                        {
                            totalCounter++;
                        }
                    
  
                }

                //todayCount.InnerText = todayCounter.ToString();
                objDashboardViewModel.TodayCount = todayCounter;
                objDashboardViewModel.YearCount = totalCounter;
                objDashboardViewModel.JanuaryCount = janCounter;
                objDashboardViewModel.FabruaryCount = febCounter;
                objDashboardViewModel.MarchCount = marCounter;
                objDashboardViewModel.AprilCount = aprCounter;
                objDashboardViewModel.MayCount = mayCounter;
                objDashboardViewModel.JuneCount = junCounter;
                objDashboardViewModel.JulyCount = julCounter;
                objDashboardViewModel.AugustCount = augCounter;
                objDashboardViewModel.SeptemberCount = sepCounter;
                objDashboardViewModel.OctoberCount = octCounter;
                objDashboardViewModel.NovemeberCount = novCounter;
                objDashboardViewModel.DecemberCount = decCounter;



                return objDashboardViewModel;
                
            }
        }
    }

Here is my View :



<div class="grid">

              <div class="grid-title">
               <div class="pull-left">
                  <div class="icon-title"><i class="icon-eye-open"></i></div>
                  <span>Dashboard</span> 
                  <div class="clearfix"></div>
               </div>
               <div class="pull-right"> 
                  <div class="btn-group" style="margin-top:4px;margin-right:4px;">
                 @* <button class="btn">Verified Today</button>*@
                  @*<button class="btn">Last Week</button>
                  <button class="btn">Last Month</button*@>
                </div>
               </div>
              <div class="clearfix"></div>   
              </div>

              <div class="clearfix"></div>

              <div class="grid-content overflow">
              
              <div style="position:relative;">
              <h3>Today's Processed</h3><span>@Model.TodayCount</span>
              <h3>2013 Total</h3><span>@Model.YearCount</span>
                  
                  <script type="text/javascript">
                      var chart1;
                      //data: [january, '@Model.FabruaryCount', '@Model.MarchCount', '@Model.AprilCount', '@Model.MayCount', '@Model.JuneCount', '@Model.JulyCount', '@Model.AugustCount', '@Model.SeptemberCount', '@Model.OctoberCount', '@Model.NovemeberCount', '@Model.DecemberCount']
                      var january = @Model.JanuaryCount;
                      $(document).ready(function () {
                          chart1 = new Highcharts.Chart({
                              chart: {
                                  type: 'spline',
                                  renderTo: 'myDiv'
                              },
                              title: {
                                  text: 'Monthly Tests Processed',
                                  x: -20 //center
                              },
                              subtitle: {
                                  text: '2013',
                                  x: -20
                              },
                              xAxis: {
                                  categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                              },
                              yAxis: {
                                  title: {
                                      text: 'No. of test processed'
                                  },
                                  plotLines: [{
                                      value: 0,
                                      width: 1,
                                      color: '#808080'
                                  }]
                              },
                              tooltip: {
                                  valueSuffix: 'Tests Processed'
                              },
                              legend: {
                                  layout: 'vertical',
                                  align: 'right',
                                  verticalAlign: 'middle',
                                  borderWidth: 0
                              },
                              series: [{
                                  name: '2013',
                                  data: [@Model.JanuaryCount, @Model.FabruaryCount, @Model.MarchCount, @Model.AprilCount, @Model.MayCount, @Model.JuneCount, @Model.JulyCount, @Model.AugustCount, @Model.SeptemberCount, @Model.OctoberCount, @Model.NovemeberCount,@Model.DecemberCount]
                              }]
                          });
                      });
    

  </script>
 <script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="myDiv" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
          
              
              
              </div>

              </div>

</div>


If you have any question you can ask me in comments. Thanks.

2 comments:

  1. this plugin is very strong in my point of view, it provides satistics charts, pie charts and much more you juct checjk out demos on it site.

    ReplyDelete