HI WELCOME TO SIRIS

creating charts using google charts in asp.net mvc

table


controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace report_kansiris.Controllers
{
    public class graphController : Controller
    {
        string DeliverTime; string restcode1;
        // GET: graph
        public ActionResult Index(string restcode)
        {
            if (restcode == null)
            { restcode = "HN"; }

            if (restcode == "HN")
            {
                restcode1 = "Himayath Nagar";
            }
            else if (restcode == "KP")
            {
                restcode1 = "Kukatpally";
            }
            else if (restcode == "AN")
            {
                restcode1 = "A.S.Rao Nagar";
            }
            ViewBag.restcode1 = restcode1;
            ViewBag.restcode = restcode;
            return View();
        }


        public ActionResult clpview(string restcode)
        {
            try
            {
                //string DeliverTime;
                if (restcode == null)
                { restcode = "HN"; }
                DeliverTime = DateTime.Today.ToString();
                Ankapurservices chartl = new Ankapurservices();
                var modelCust = chartl.chartline(DeliverTime, restcode);
                var data = String.Join(",", modelCust.OrderByDescending(m=>m.OrderDate).Select(m => Convert.ToDateTime(m.OrderDate).ToString("dd-MM-yyyy")).ToList());
                ViewBag.time = data;
                ViewBag.orders = String.Join(",", modelCust.OrderByDescending(m => m.OrderDate).Select(m => m.Orders).ToList());
                return PartialView("clpview", modelCust);
            }
            catch (Exception)
            {
                return Content("<script language='javascript' type='text/javascript'>alert('Restaurant is closed at the moment');location.href='" + @Url.Action("Index", "graph") + "'</script>");
            }
        }

        [ChildActionOnly]
        public ActionResult chpie2view(string restcode)
        {
            try
            {
                if (restcode == null)
            { restcode = "HN"; }
            DeliverTime = DateTime.Today.ToString();
            Ankapurservices chartl = new Ankapurservices();
            var modelCust1 = chartl.chartpie(DeliverTime, restcode);
            ViewBag.ordertype = String.Join(",", modelCust1.Select(m => m.Ordertype).ToList());
            ViewBag.orders1 = String.Join(",", modelCust1.Select(m => m.Orders).ToList());
            return PartialView("chpie2view", modelCust1);
            }
            catch (Exception)
            {
                return Content("<script language='javascript' type='text/javascript'>alert('Restaurant is closed at the moment');location.href='" + @Url.Action("Index", "graph") + "'</script>");
            }
        }

        [ChildActionOnly]
        public ActionResult cbpview(string restcode)
        {
            try
            {
                //string DeliverTime;

                if (restcode == null)
            { restcode = "HN"; }
            DeliverTime = DateTime.Today.ToString();
            Ankapurservices chartl = new Ankapurservices();
            var modelCust2 = chartl.chartbar(DeliverTime, restcode);
            //ViewBag.time = modelCust.Select(m => Convert.ToDateTime(m.OrderDate).ToString("yyyy-MM-dd")).ToList();
            var data = String.Join(",", modelCust2.Select(m => Convert.ToDateTime(m.month).ToString("MMMM-yyyy")).ToList());
            //ViewBag.time = String.Join(",", modelCust.Select(m => Convert.ToDateTime(m.OrderDate).ToString("MMM dd")).ToList());
            //var date1 = data.Split(',');
            var result = string.Join(",", data);

            ViewBag.time2 = result;
            ViewBag.orders2 = String.Join(",", modelCust2.Select(m => m.count).ToList());
            return PartialView("cbpview", modelCust2);
            }
            catch (Exception)
            {
                return Content("<script language='javascript' type='text/javascript'>alert('Restaurant is closed at the moment');location.href='" + @Url.Action("Index", "graph") + "'</script>");
            }
        }

    }
}


entity framework ado.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using report_ankapur.Models;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Mvc;
using System.Globalization;

namespace report_ankapur
{
    public class Ankapurservices
    {

 public List<chartline> chartline(string DeliverTime, string restcode)
        {
            try
            {
                GetConnectionString getConnectionString = new GetConnectionString();
                string ConnectionString = getConnectionString.CustomizeConnectionString(restcode);
                SqlConnection Conn = new SqlConnection(ConnectionString);

                Conn.Open();
                DateTime DeliverTime1 = Convert.ToDateTime(DeliverTime);



                List<chartline> _chartlines = new List<chartline>();


                if (Conn.State != System.Data.ConnectionState.Open)
                    Conn.Open();

                SqlCommand cmd = new SqlCommand("spchartline", Conn);
                cmd.Parameters.AddWithValue("@from_date", DeliverTime1);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader _Reader = cmd.ExecuteReader();

                while (_Reader.Read())
                {
                    chartline chartl = new chartline();
                    //    chartl.OrderDate = DateTime.ParseExact((_Reader["OrderDate"].ToString()), "ddd MMM dd yyyy HH:mm:ss", CultureInfo.InvariantCulture);
                    chartl.OrderDate = Convert.ToDateTime((_Reader["OrderDate"].ToString()));

                    chartl.Orders = _Reader[""].ToString();
                    _chartlines.Add(chartl);

                }

                return _chartlines;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //if (Conn != null)
                //{
                //    if (Conn.State == ConnectionState.Open)
                //    {
                //        Conn.Close();
                //        Conn.Dispose();
                //    }
                //}
            }
        }
        public List<chartline> chartpie(string DeliverTime, string restcode)
        {
            try
            {
                GetConnectionString getConnectionString = new GetConnectionString();
                string ConnectionString = getConnectionString.CustomizeConnectionString(restcode);
                SqlConnection Conn = new SqlConnection(ConnectionString);
                Conn.Open();
                DateTime DeliverTime1 = Convert.ToDateTime(DeliverTime);



                List<chartline> _chartlines = new List<chartline>();


                if (Conn.State != System.Data.ConnectionState.Open)
                    Conn.Open();

                SqlCommand cmd = new SqlCommand("spchartpie", Conn);
                cmd.Parameters.AddWithValue("@from_date", DeliverTime1);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader _Reader = cmd.ExecuteReader();

                while (_Reader.Read())
                {
                    chartline chartl = new chartline();
                    chartl.Ordertype = _Reader["Ordertype"].ToString();
                    chartl.Orders = _Reader[""].ToString();
                    _chartlines.Add(chartl);

                }

                return _chartlines;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //if (Conn != null)
                //{
                //    if (Conn.State == ConnectionState.Open)
                //    {
                //        Conn.Close();
                //        Conn.Dispose();
                //    }
                //}
            }
        }

        public List<chartbar> chartbar(string DeliverTime, string restcode)
        {
            try
            {
                GetConnectionString getConnectionString = new GetConnectionString();
                string ConnectionString = getConnectionString.CustomizeConnectionString(restcode);
                SqlConnection Conn = new SqlConnection(ConnectionString);

                Conn.Open();
                DateTime DeliverTime1 = Convert.ToDateTime(DeliverTime);



                List<chartbar> _chartbars = new List<chartbar>();


                if (Conn.State != System.Data.ConnectionState.Open)
                    Conn.Open();

                SqlCommand cmd = new SqlCommand("spchartbar", Conn);
                cmd.Parameters.AddWithValue("@from_date", DeliverTime1);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader _Reader = cmd.ExecuteReader();

                while (_Reader.Read())
                {
                    chartbar chartbar = new chartbar();
                    chartbar.count = _Reader["count"].ToString();
                    chartbar.month = _Reader["month"].ToString();
                    _chartbars.Add(chartbar);

                }

                return _chartbars;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //if (Conn != null)
                //{
                //    if (Conn.State == ConnectionState.Open)
                //    {
                //        Conn.Close();
                //        Conn.Dispose();
                //    }
                //}
            }
        }
}
}


View code:

@model report_ankapur.Models.chartline
@{
    ViewBag.Title = "Graph";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<title>
    @ViewBag.Title
</title>

<ol class="breadcrumb">
    <li class="breadcrumb-item">
        <a >  Dashboard   </a>
    </li>
    <li class="breadcrumb-item active">
        <a>Ankapurchicken Graph</a> Restaurant:<b> &nbsp; @ViewBag.restcode1 &nbsp;</b>
    </li>
    <div class="col-xs-12">
        <select id="restcode" name="restcode">
            <option value="">select restaurant</option>
            <option value="AN">A.S.Rao Nagar</option>
            <option value="HN">Himayath Nagar</option>
            <option value="KP">Kukatpally</option>
        </select>
    </div>
</ol>

<!-- Example Pie Chart Card-->
@*<div class="card mb-3">
        <div class="card-header">
            <i class="fa fa-area-chart"></i> Area Chart Example
        </div>
        <div class="card-body">
            @{Html.RenderAction("clpview", "chartsline");}
        </div>
    </div>*@


    <!-- Area Chart Example-->
<div class="card mb-3">
    <div class="card-header">
        <i class="fa fa-area-chart"></i> Sales per Date for Last 31  days
    </div>
  
  
      
        @{
            Html.RenderAction("clpview", "graph", new {restcode = @ViewBag.restcode });
            }

 
    <div class="card-footer small text-muted"></div>
</div>
<div class="row">
    <div class="col-lg-8">
        <!-- Example Bar Chart Card-->
        <div class="card mb-3">
            <div class="card-header">
                <i class="fa fa-bar-chart"></i> Sales per Month
            </div>

            @{
                Html.RenderAction("cbpview", "graph", new { restcode = @ViewBag.restcode });
            }
             


           
            <div class="card-footer small text-muted"></div>
        </div>
    </div>

    <div class="col-lg-4">
        <!-- Example Pie Chart Card-->
        <div class="card mb-3">
            <div class="card-header">
                <i class="fa fa-pie-chart"></i> Sales per Type from Last 30 days
            </div>
     

            @{
                Html.RenderAction("chpie2view", "graph", new { restcode = @ViewBag.restcode });
            }
              
     
            <div class="card-footer small text-muted"></div>
        </div>
    </div>
</div>
    <!-- Example DataTables Card-->
    @*@{Html.RenderAction("clp2view", "chartsline");}*@
<script src="/Scripts/jquery-1.12.4.js"></script>

<script>
      $("#restcode").change(function () {
                                var restcode = $('option:selected', $(this)).val();
                                location.href = "/graph/Index?restcode=" + restcode;
                            });

</script>

Partial View -clpview:


<fieldset>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>

    <script type="text/javascript">


        google.load("visualization", "1", { packages: ["corechart"] });
        google.setOnLoadCallback(drawChart);

        function drawChart() {
            var dates = '@ViewBag.time';
             var date1 = dates.split(',');
            var orders1 = [@ViewBag.orders];

            var data = new google.visualization.DataTable();
             data.addColumn('string', 'dates');
            data.addColumn('number', 'orders');
            for (i = 0; i < date1.length; i++) {
                data.addRow([date1[i].toString(), orders1[i]]);
            }
            var options = {
                title: 'Ankapurchicken Sales per Date',
                curveType: 'function',
                legend: { position: 'bottom' },
                hAxis: {
                    title: 'date', titleTextStyle: { color: 'blue' }
                       }
            };

            //Different chart types >> AreaChart , BubbleChart ,LineChart ,ScatterChart

          //var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
            //var chart = new google.visualization.BubbleChart(document.getElementById('chart_div'));
            var chart = new google.visualization.LineChart(document.getElementById('chart_div1'));
           // var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }
    </script>
    <div id="chart_div1"  width="100%" height="700">
    </div>
</fieldset>


Partial View -chpie2view:

 <fieldset>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>

    <script type="text/javascript">


        google.load("visualization", "1", { packages: ["corechart"] });
        google.setOnLoadCallback(drawChart);

        function drawChart() {
            var dates = '@ViewBag.ordertype';
            var date1 = dates.split(',');
            var orders1 = [@ViewBag.orders1];

            var data = new google.visualization.DataTable();
            data.addColumn('string', 'dates');
            data.addColumn('number', 'orders');
            for (i = 0; i < date1.length; i++) {
                data.addRow([date1[i].toString(), orders1[i]]);
            }
            var options = {
                title: 'Ankapurchicken Sales per Type',
                hAxis: {
                    title: 'date', titleTextStyle: { color: 'blue' }
                }
            };

            //Different chart types >> AreaChart , BubbleChart ,LineChart ,ScatterChart
            var chart = new google.visualization.PieChart(document.getElementById('chart_div2'));

            //var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
            //var chart = new google.visualization.BubbleChart(document.getElementById('chart_div'));
            //var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            // var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }
    </script>
    <div id="chart_div2" width="100%" height="100">
    </div>
</fieldset>



Partial View -cbpview:

  <fieldset>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>

    <script type="text/javascript">


        google.load("visualization", "1", { packages: ["corechart"] });
        google.setOnLoadCallback(drawChart);

        function drawChart() {
            var dates = '@ViewBag.time2';
            var date1 = dates.split(',');
            var orders1 = [@ViewBag.orders2];

            var data = new google.visualization.DataTable();
            data.addColumn('string', 'dates');
            data.addColumn('number', 'orders');
            for (i = 0; i < date1.length; i++) {
                data.addRow([date1[i].toString(), orders1[i]]);
            }
            var options = {
                title: 'Ankapur chicken orders',
                hAxis: {
                    title: 'month', titleTextStyle: { color: 'blue' }
                }
            };

            //Different chart types >> AreaChart , BubbleChart ,LineChart ,ScatterChart
            //var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
            //var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
            var chart = new google.visualization.ColumnChart(document.getElementById('chart_div3'));
            //var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
            //var chart = new google.visualization.BubbleChart(document.getElementById('chart_div'));
            //var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            // var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }
    </script>
    <div id="chart_div3" width="100%" height="50">
    </div>
</fieldset>