Home > other >  ASP.NET MVC Problem with JSON and Google Charts
ASP.NET MVC Problem with JSON and Google Charts

Time:08-30

I have problem with Google Charts in ASP.NET MVC, specifically with Ajax and JS. I don't use model. Method AjaxMethod return data in JSON format as query result. Problem is with View.
This is my Controller:

using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;
using System.Linq;
using SARSCOV2.ModelsDB;
using System;
using System.Web.Services;

namespace SARSCOV2.Controllers
{
    public class HistogramController : Controller
    {
        DBEntities db = new DBEntities();

        public ActionResult Index()
        {
            var wojewodztwo = (from r in db.wojewodztwa select r.wojewodztwo).OrderBy(r => r).ToList();
            ViewBag.wojewodztwo = new SelectList(wojewodztwo, "wojewodztwo");
            return View();
        }

        [HttpPost]
        public JsonResult AjaxMethod(DateTime start, DateTime stop, String wojewodztwo)
        {
            string query = "SELECT stan_rekordu_na ,zgony FROM woj_target WHERE wojewodztwo =@wojewodztwo  AND "  
                "stan_rekordu_na BETWEEN "  
                "@start AND @stop";
            string constructor = ConfigurationManager.ConnectionStrings["C2"].ConnectionString;
            List<object> chart_data = new List<object>();
                        chart_data.Add(new object[]
                        {  "zgony"
                           
                        });
            using (SqlConnection connection = new SqlConnection(constructor))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = connection;
                    cmd.Parameters.AddWithValue("@start", start);
                    cmd.Parameters.AddWithValue("@stop", stop);
                    cmd.Parameters.AddWithValue("@wojewodztwo", wojewodztwo);
                    connection.Open();
                    using (SqlDataReader sql_data_reader = cmd.ExecuteReader())
                    {
                        while (sql_data_reader.Read())
                        {
                            chart_data.Add(new object[]{ 
                                sql_data_reader["zgony"]}
                            
                            );
                        }
                    }
                    connection.Close();
                }
            }
            return Json(chart_data);
        }
    }
}

And this is my View.

<html>
<head>
@{
    ViewBag.Title = "Index";
}
<!--Histogram dla województw-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        google.charts.load('current', { 'packages': ['corechart'] });
        $('#btnDisplay').on('click', function () {
            var start = $("stop").find("option:selected").val();
            var stop = $("start").find("option:selected").val();
            var wojewodztwo = $("wojewodztwo").find("option:selected").val();

            drawChart(start, stop, wojewodztwo);
            return false;
        });
        function drawChart(start, stop, wojewodztwo) {
            var obj = {};
            obj.start = start;
            obj.stop = stop;
            obj.stop = wojewodztwo;

            $.ajax({
                url: "/Histogram/AjaxMethod",
                data: JSON.stringify(obj),
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            }).done(function (data) {
                var options = {
                };
                var data = google.visualization.arrayToDataTable(data.d);
                var chart = new google.visualization.Histogram(document.getElementById('divChart'));
                chart.draw(data, options);
            }).fail(function (err) {
                console.log(err);
            }).error(function (err) {
                console.log(err);
            });
        }
    });
</script>

</head>
<body>
@using (Html.BeginForm("AjaxMethod", "Histogram", FormMethod.Post))
 {
    <h4>Histogram zgonów dla województw</h4>
    @Html.DropDownList("wojewodztwo", (SelectList)ViewBag.wojewodztwo, new { @class = "form-control" })
    <span>Data początkowa:</span>
    <input type="date" id="start" name="start" value="2021-01-28" min="2021-01-28" />
    <span>Data końcowa:</span>
    <input type="date" id="stop" name="stop" value="2021-01-28" min="2021-01-28" />
    <input type="submit" id="btnDisplay" value="Wyszukaj" CssClass="btn btn-link">
    <br />
    <div id="divChart">
    </div>
 }
    </body>
</html>

It returns the correct values but I don't know how to correct the view to show the histogram.Maybe someone knows how to fix it? This is returned

CodePudding user response:

google's load statement returns a promise to let you know when google charts has loaded.

AND google's load statement waits on the page to load by default,
so you can actually use google.load in place of $(document).ready,
as follows...

google.charts.load('current', {'packages': ['corechart']}).then(function () {
    $('#btnDisplay').on('click', function () {
        var start = $("stop").find("option:selected").val();
        var stop = $("start").find("option:selected").val();
        var wojewodztwo = $("wojewodztwo").find("option:selected").val();

        drawChart(start, stop, wojewodztwo);
        return false;
    });
    function drawChart(start, stop, wojewodztwo) {
        var obj = {};
        obj.start = start;
        obj.stop = stop;
        obj.stop = wojewodztwo;

        $.ajax({
            url: "/Histogram/AjaxMethod",
            data: JSON.stringify(obj),
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (data) {
            var options = {
            };
            var data = google.visualization.arrayToDataTable(data.d);
            var chart = new google.visualization.Histogram(document.getElementById('divChart'));
            chart.draw(data, options);
        }).fail(function (err) {
            console.log(err);
        }).error(function (err) {
            console.log(err);
        });
    }
});

CodePudding user response:

I did as you suggested. Still to no effect. It shows the following errors.enter image description here

CodePudding user response:

I wonder if maybe the controller data is not JSON format? There should be an array of objects like this ....[{"deaths": 12},{"deaths":32},...] and not for example [["deaths"],[12],[6],[1]]. But for one parameter it shows this structure and works and for multiple it doesn't work. Maybe the error is in data: JSON.stringify(obj) ?

  • Related