score:9

Accepted answer

here is a simple demo like below:

1.model:

public class job
{
    public int jobid { get; set; }
    public string jobname { get; set; }
    public string jobstatus { get; set; }
    public datetime jobcompletion { get; set; }
}

2.view:

<canvas id="canvas" width="400" height="400"></canvas>
@section scripts{
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.8.0/chart.bundle.js" integrity="sha256-qsishlknror4j8gmhrlw3fgkrpki733tlq+qemcr05q=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.8.0/chart.bundle.min.js" integrity="sha256-xkeoj50pzbugkpqxdyhd7o7hxe0laogeguuidbq6vis=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.8.0/chart.css" integrity="sha256-ivm9njf/b5l2roebifno92e5onttvyaeesdemdc6iqa=" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.8.0/chart.js" integrity="sha256-armsf+3jjk2lotgqxfnujpftu4hak57mtipdfpihxou=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.8.0/chart.min.css" integrity="sha256-aa0xajgmk/x74wm224kmqenqc2xykwlat08ozqjef0e=" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.8.0/chart.min.js" integrity="sha256-uv9bnbucvcpipkq2ns9wypjmi8dtoefta/nh2aojalw=" crossorigin="anonymous"></script>
    <script>
        function getjson_simple() {
          var resp = [];
              $.ajax({
                  type: "get",
                  url: '/jobs/index',
                  async: false,
                  contenttype: "application/json",
                  success: function (data) {
                      resp.push(data);
                  },
                  error: function (req, status, error) {
                      // do something with error
                      alert("error");
                  }
              });
          return resp;
     }
        var simpledata = getjson_simple();
        var ctx = document.getelementbyid("canvas")
        var linechartdata = {
            labels: simpledata[0].mydate, 
            datasets: [{
                label: 'sucess',
                bordercolor: "mediumseagreen",
                backgroundcolor: "mediumseagreen",
                fill: false,
                data:   simpledata[0].mysuccess,
                yaxisid: 'y-axis-1',
            }, {
                label: 'exceptioned',
                bordercolor: "tomato",
                backgroundcolor: "tomato",
                fill: false,
                data: simpledata[0].myexception,
                yaxisid: 'y-axis-2'
            }]
        };

        window.myline = chart.line(ctx, {
            data: linechartdata,
            options: {
                responsive: true,
                hovermode: 'index',
                stacked: false,
                title: {
                    display: true,
                    text: 'processes'
                },
                scales: {
                    yaxes: [{
                        type: 'linear',
                        display: true,
                        position: 'left',
                        id: 'y-axis-1',
                    }, {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        id: 'y-axis-2',

                        // grid line settings
                        gridlines: {
                            drawonchartarea: false, // only want the grid lines for one axis to show up
                        },
                    }],
                }
            }
        });

    </script>
}

3.controller:

public class jobscontroller : controller
{
    private readonly yourcontext _context;

    public jobscontroller(yourcontext context)
    {
        _context = context;
    }

    // get: jobs
    public async task<actionresult> index()
    {
        var date = await _context.job.select(j => j.jobcompletion).distinct().tolistasync();
        var success =_context.job
            .where(j => j.jobstatus == "success")
            .groupby(j => j.jobcompletion)
            .select(group=>new {
                jobcompletion = group.key,
                count=group.count()
            });
        var countsuccess = success.select(a => a.count).toarray();
        var exception = _context.job
            .where(j => j.jobstatus == "exception")
            .groupby(j => j.jobcompletion)
            .select(group => new {
                jobcompletion = group.key,
                count = group.count()
            });
        var countexception = exception.select(a => a.count).toarray();
        return new jsonresult(new { mydate=date,mysuccess= countsuccess, myexception= countexception });
    }
}

4.database:

enter image description here

5.result:

enter image description here

score:0

<%@ page language="c#" autoeventwireup="true" codefile="default.aspx.cs" inherits="_default" %>

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="jquery-3.3.1.min.js" type="text/javascript"></script>
    <script src="chart.js" type="text/javascript"></script>

</head>
<body>
    <form id="form1" runat="server">
    

    <select id="ddlyear">
    <option>2010</option>
    <option>2011</option>
    <option>2012</option>
    <option>2013</option>
    <option>2014</option>
    <option>2015</option>
</select>

<select id="ddlmonth">
    <option value="1">jan</option>
    <option value="2">feb</option>
    <option value="3">mar</option>.......... ...........</select>
<button id="btngeneratepiechart">show</button>
<br/>

<script type="text/javascript">

    $(document).ready(function () {

        $("btngeneratepiechart").on('click', function (e) {
            e.preventdefault();
            var gdata = [];
            gdata[0] = $("#ddlyear").val();
            gdata[1] = $("#ddlmonth").val();

            var jsondata = json.stringify({
                gdata: gdata
            });
            $.ajax({
                type: "post",
                url: "webservice.asmx/gettrafficsourcedata",
                data: jsondata,
                contenttype: "application/json; charset=utf-8",
                datatype: "json",
                success: onsuccess_,
                error: onerrorcall_
            });

            function onsuccess_(response) {
                var adata = response.d;
                var arr = [];
                $.each(adata, function (inx, val) {
                    var obj = {};
                    obj.color = val.color;
                    obj.value = val.value;
                    obj.label = val.label;
                    arr.push(obj);
                });
                var ctx = $("#mychart").get(0).getcontext("2d");
                var mypiechart = new chart(ctx).pie(arr);
            }

            function onerrorcall_(response) { }
            e.preventdefault();
        });
    });

</script>


<canvas id="mychart" width="200" height="200"></canvas>


    </form>
</body>
</html>

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using system.data;
using system.text;
using system.web.services;
using system.data.sqlclient;
using system.configuration;

public partial class _default : system.web.ui.page
{
    protected void page_load(object sender, eventargs e)
    {

    }

    public class trafficsourcedata
    {
        public string label { get; set; }
        public string value { get; set; }
        public string color { get; set; }
        public string hightlight { get; set; }
    }

    [webmethod]

    public list<trafficsourcedata> gettrafficsourcedata(list<string> gdata)
    {
        list<trafficsourcedata> t = new list<trafficsourcedata>();
        string[] arrcolor = new string[] { "#231f20", "#ffc200", "#f44937", "#16f27e", "#fc9775", "#5a69a6" };

        string conn = configurationmanager.connectionstrings["constring"].connectionstring;

        using (sqlconnection cn = new sqlconnection(conn))
        {
            string myquery = "select * from traffic_data where year =@year and month=@month";
            sqlcommand cmd = new sqlcommand();
            cmd.commandtext = myquery;
            cmd.commandtype = commandtype.text;
            cmd.parameters.addwithvalue("@year", gdata[0]);
            cmd.parameters.addwithvalue("@month", gdata[1]);
            cmd.connection = cn;
            cn.open();
            sqldatareader dr = cmd.executereader();
            if (dr.hasrows)
            {
                int counter = 0;
                while (dr.read())
                {
                    trafficsourcedata tsdata = new trafficsourcedata();
                    tsdata.value = dr["visit_count"].tostring();
                    tsdata.label = dr["traffic_source"].tostring();
                    tsdata.color = arrcolor[counter];
                    t.add(tsdata);
                    counter++;
                }
            }
        }
        return t;
    }

}

Related Query

More Query from same tag