Populate CanvasJS line chart from JsonResult in ASP.Net MVC

smcdevelopments
 
on May 17, 2022 10:55 PM
Sample_558505.zip
881 Views

In my ASP.NET MVC application, there is a line chart in which I want to show record counts and the month on X-axis and Y-axis.

So I'm trying to call an Ajax to the controller and the model has a record created date and the value.

This is the JavaScript of the chart, here in the data I want to return the count of records and for labels months.

Currently, it has dummy data.

var bouData = {
    // Generate the days labels on the X axis.
    labels: Array.from(new Array(30), function (_, i) {
      return i === 0 ? 1 : i;
    }),
    datasets: [{
          label: 'Satisfied',
          fill: 'start',
          data: [1500, 800, 320, 180, 240, 320, 230, 650, 590, 1200, 750, 940, 1420, 1200, 960, 1450, 1820, 2800, 2102, 1920, 3920, 3202, 3140, 2800, 3200, 3200, 3400, 2910, 3100, 4250],
          backgroundColor: 'rgba(0,123,255,0.1)',
          borderColor: 'rgba(0,123,255,1)',
          pointBackgroundColor: '#ffffff',
          pointHoverBackgroundColor: 'rgb(0,123,255)',
          borderWidth: 1.5,
          pointRadius: 0,
          pointHoverRadius: 3
        },

So in the controller, I want to return JsonResult and bind to labels as month and data as count.

This is my incomplete controller code.

var satisfied = db.tbl_Main.Where(m => m.TotalSatisfaction >= 12).GroupBy(
                            m => new { m.CreatedDate.Year, m.CreatedDate.Month },
                            m => m.TotalSatisfaction
                            )
                            .Select(g => new
                            {
                                label = new DateTime(g.Key.Year, g.Key.Month, 1),
                            data = g.Sum()
                            })
                            .ToList();

I would appreciate it if you can suggest if there is another way of doing this easily or how to complete this.

In the end, What I want to return is, 

* tbl_Main contains the record as Datetime.

* I want to get the sum of the count of the same month.

* Return example

January 10

February 30

March 18

Likewise month with record count.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on May 19, 2022 02:55 AM

Hi smcdevelopmen...,

Refer below sample.

Model

public class DataModel
{
    public string x { get; set; }
    public int y1 { get; set; }
    public int y2 { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult AjaxMethod()
    {
        List<DataModel> datas = new List<DataModel>();
        datas.Add(new DataModel { x = "January", y1 = 100, y2 = 50 });
        datas.Add(new DataModel { x = "February", y1 = 150, y2 = 200 });
        datas.Add(new DataModel { x = "March", y1 = 200, y2 = 60 });

        return Json(datas);
    }
}

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethod",
                data: {},
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    var dps1 = [], dps2 = [];
                    for (var i = 0; i < data.length; i++) {
                        dps1.push({ label: data[i].x, y: data[i].y1 });
                        dps2.push({ label: data[i].x, y: data[i].y2 });
                    }
                    var chart = new CanvasJS.Chart("chartContainer", {
                        title: {
                            text: "MultiSeries Chart"
                        },
                        data: [
                            {
                                type: "line", dataPoints: dps1
                            },
                            {
                                type: "line", dataPoints: dps2
                            }
                        ]
                    });
                    chart.render();
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    </script>
</head>
<body>
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>

Screenshot