Bind multiple Chart from database using jQuery Ajax in ASP.Net MVC

doram
 
on Oct 30, 2021 03:00 AM
629 Views

I am using the following example to bind graphs

Google Charts in ASP.Net MVC: Google (Pie / Doughnut) Chart example with database in ASP.Net MVC

Which is working fine I would like to bind 4 different graphs in the same call is it possible to do that

I will have an sp which retruns multiple tables. I would like to separate the graphs and show it.

Sample data

Type   Name   Count

  G1      ABC         10

  G1      DEF         2

  G2      XYZ         2

WHere G1 and G2 are meant to Graph1 and Graph2

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Oct 31, 2021 11:59 AM
on Nov 01, 2021 08:53 AM

Hi doram,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

Namespaces

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Controller

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

    [HttpPost]
    public JsonResult AjaxMethod()
    {
        string query = "SELECT ShipCountry,ShipCity, COUNT(orderid) TotalOrders FROM Orders WHERE ShipCountry = 'France' GROUP BY ShipCity,ShipCountry ";
        query += "UNION ";
        query += "SELECT ShipCountry,ShipCity, COUNT(orderid) TotalOrders FROM Orders WHERE ShipCountry = 'UK' GROUP BY ShipCity,ShipCountry ";
        string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
        List<object> chartData = new List<object>();
        chartData.Add(new object[] { "ShipCity", "TotalOrders", "ShipCountry" });
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        chartData.Add(new object[] { sdr["ShipCity"], sdr["TotalOrders"], sdr["ShipCountry"] });
                    }
                }

                con.Close();
            }
        }

        return Json(chartData);
    }
}

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <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() {
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethod",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var chartDatas = new Array();
                    chartDatas.push(AddData(r[0]));
                    var key = "";
                    var status = false;
                    for (var i = 1; i < r.length; i++) {
                        if (key == "") {
                            key = r[i][2];
                            chartDatas.push(AddData(r[i]));
                        } else if (key == r[i][2]) {
                            chartDatas.push(AddData(r[i]));
                            if (i == r.length - 1) {
                                status = true;
                            }
                        } else {
                            status = true;
                        }

                        if (status) {
                            var options = { title: key + ' City Distribution' };
                            var data = google.visualization.arrayToDataTable(chartDatas);
                            var dvChart = $("<div style='width: 500px; height: 400px' />");
                            var chart = new google.visualization.PieChart($(dvChart)[0]);
                            chart.draw(data, options);
                            $('#dvCharts').append(dvChart);
                            key = r[i][2];
                            chartDatas = [chartDatas[0]];
                            chartDatas.push(AddData(r[i]));
                            status = false;
                        }
                    }
                },
                error: function (r) {
                    alert(r.responseText);
                }
            });
        }

        function AddData(data) {
            var chartData = [];
            for (var j = 0; j < data.length - 1; j++) {
                chartData.push(data[j]);
            }

            return chartData;
        }
    </script>
    <div id="dvCharts"></div>
</body>
</html>

Screenshot