0

I'm trying to bind the query to google charts but I face a problem as shown below. I'm new to asp.net core so when I try to use google charts I face this problem and below are my codes any help please or any other free charts you advise me to use

Hello everyone, I'm trying to bind the query to google charts but I face the problem as shown below. I'm new to asp.net core so when I try to use google charts I face this problem and below are my codes any help please or any other free charts you advise me to use

 public JsonResult AjaxMethod(IConfiguration config)
        {

            string query = "select [UserId], count([ServiceOrderNumber]) as ServiceOrders from [dbo].[ServiceOrders] group by [UserId] order by count ([ServiceOrderNumber]) desc";

            string constr = this.configuration.GetConnectionString("DefaultConnection");

            List<object> chartData = new List<object>();
            chartData.Add(new object[]
                            {
                            "[UserId]", "[ServiceOrders]"
                            });
            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["[UserId]"], sdr["[ServiceOrders]"]
                            });
                        }
                    }

                    con.Close();
                }
            }

            return Json(chartData);
        }

and this is my 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: "/Reports/AjaxMethod",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var data = google.visualization.arrayToDataTable(r);

                    //Pie
                    var options = {
                        title: 'USA City Distribution'
                    };
                    var chart = new google.visualization.PieChart($("#chart")[0]);
                    chart.draw(data, options);
                },
                failure: function (r) {
                    alert(r.d);
                },
                error: function (r) {
                    alert(r.d);
                }
            });
        }
    </script>
    <div id="chart" style="width: 500px; height: 400px;">
    </div>
</body>
</html>
Pritom Sarkar
  • 2,154
  • 3
  • 11
  • 26
Hama Mod
  • 33
  • 10
  • HTTP Status code 500 means something went wrong in your application. Did you able to get a JSON result from the specific endpoint? From the code, you're expecting a config object in the server-side method, but from the client, you're sending an empty object. Try to send a request from Postman or some tools and check what response you're getting from backend. – Anuraj Mar 08 '21 at 00:47
  • Try to add break point in the AjaxMethod and the ajax success function, then, step by step to debug your code. Check whether the AjaxMethod executed successfully, and return the correct data. Besides, please check the table structure in the database and the `chartData` list, are you sure the column name or property name contains the **'[]'**, try to remove them. – Zhi Lv Mar 08 '21 at 02:38
  • dears thanks for your replies what i receive from my controller is that {[["UserId","OrderNum"],["bb6be3ed-aa33-4dea-8980-ef29f7f984bd",3],["730e9454-a374-4ddc-8bc1-8c6c4e89bd97",1]]} and they are the data i want to be shown as chart even if my view has no codes it still be showing like this. – Hama Mod Mar 08 '21 at 08:51

1 Answers1

1
public JsonResult AjaxMethod(IConfiguration config)

The 500 error relates the AjaxMethtod parameter:IConfiguration config. From your code, it seems that you want to get the connection string via the IConfiguration, in this scenario, you could use constructor injection to resolve an IConfiguration, instead of transferring it as the parameter. So, try to remove it from the AjaxMethod.

The sample code as below:

public class ReportsController : Controller
{
    private readonly ApplicationDbContext _context;
    //Required using Microsoft.Extensions.Configuration;
    private readonly IConfiguration _configuration;
    public ReportsController(ApplicationDbContext context, IConfiguration configuration)
    {
        _context = context;
        _configuration = configuration;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult AjaxMethod()
    {
        var conectionstring = this._configuration.GetConnectionString("DefaultConnection");
        List<object> chartData = new List<object>();
        chartData.Add(new object[]
                        {
                        "[UserId]", "[ServiceOrders]"
                        });
         
        //based on the connection string to query database and get data.
        for (int i = 1; i < 10; i++)
        {
            chartData.Add(new object[]
                        {
                         new Guid(), i
                        });
        }
        return Json(chartData);
    }
}

Code in the Index View page:

<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: "/Reports/AjaxMethod",
                //contentType: "application/json; charset=utf-8",
                //dataType: "json",
                success: function (r) {
                    var data = google.visualization.arrayToDataTable(r);

                    //Pie
                    var options = {
                        title: 'USA City Distribution'
                    };
                    var chart = new google.visualization.PieChart($("#chart")[0]);
                    chart.draw(data, options);
                },
                failure: function (r) {
                    alert(r.d);
                },
                error: function (r) {
                    alert(r.d);
                }
            }); 
        }
</script>
<div id="chart" style="width: 500px; height: 400px;">
</div>

Then, debugging the web application, the screenshot as below:

enter image description here

Zhi Lv
  • 18,845
  • 1
  • 19
  • 30
  • i did it but i still have problem when i remove [httppost] from the controller json data appear when i write it it gives me error 405 in the browser can you help me please this really made me so tired. – Hama Mod Mar 09 '21 at 12:56
  • 1
    Hi @HamaMod, please check your Ajax method, since it uses the `Post` method, so we should add the `[HttpPost]` attribute in the controller, if you are using `Get` method in the Ajax method, there is no need to add the '[HttpGet]` attribute in the controller. – Zhi Lv Mar 11 '21 at 09:34