Hama Mod
Hama Mod

Reputation: 33

how to create charts in asp.net core

what i want to do is creating charts from excuted data from a query in asp.net core but i face problem in usnig [httppost] in the controller when i use it gives me error 405 and when i don't use it the json data appear in the view and below are my codes.

Hello, what i want to do is creating charts from excuted data from a query in asp.net core but i face problem in usnig [httppost] in the controller when i use it gives me error 405 and when i don't use it the json data appear in the view and below are my codes.

 public JsonResult Index()
        {

            string query = "select UserId, count(ServiceOrderNumber)  as OrderNum 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", "OrderNum"

                            });

            SqlConnection con = new SqlConnection(constr);

            SqlCommand cmd = new SqlCommand(query);

            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            SqlDataReader sdr = cmd.ExecuteReader();


            while (sdr.Read())
            {
                chartData.Add(new object[]
                {
                            sdr["UserId"], sdr["OrderNum"]
                });
            }


            con.Close();

            return Json(chartData);
        }

and my view is

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>



    <script type="text/javascript">
        google.load("visualization", "1", { packages: ["corechart"] });
        google.setOnLoadCallback(drawChart);
        function drawChart() {
            $.ajax({
                type: "POST",
                url: "/Reports/Index/",
                contentType: "application/json; charset=utf-8",
                cache: false,
                traditional: true, 
                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>

Upvotes: 0

Views: 1697

Answers (1)

Rena
Rena

Reputation: 36705

i face problem in usnig [httppost] in the controller when i use it gives me error 405

The address bar of browser only support Get request.If you send the post request in browser address bar,it will get http 405 method not allowed error.

when i don't use it the json data appear in the view and below are my codes.

If you remove HttpPost,it will be HttpGet by default.So when you enter the url in address bar,you will get the json string.

Also you may misunderstand ajax,ajax will be sent after your view has loaded.

You could check the document:

AJAX is a developer's dream, because you can:
Request data from a server - after the page has loaded

So,what you need do first is to send get request to backend to load the view and then it will hit the ajax you wrote. The whole principle you could check the gif below.

Here is a whole working demo:

Index.cshtml View in Views/Reports folder:

@{
    Layout = null;
}

<!DOCTYPE html>    
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>   //be sure add jquery....
   
    <script type="text/javascript">
        google.load("visualization", "1", { packages: ["corechart"] });
        google.setOnLoadCallback(drawChart);
        function drawChart() {
            $.ajax({
                type: "POST",
                url: "/Reports/Index/",

                //url:"/Reports/GetJson/"  //if you do not use route attribute in action
                
                contentType: "application/json; charset=utf-8",
                cache: false,
                traditional: true,
                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>

Controller:

public class ReportsController : Controller
{
    //default is httpget
    public ActionResult Index()
    {
        return View();  //it is used to load the view..
    }

   //if your request url is the same with get method,you could add route attribute.
   //Because the controller could not have two same name method with the same parameter although they are used in different http request
   [Route("Reports/Index")]       
   [HttpPost] 
    public JsonResult GetJson()
    {
        List<object> chartData = new List<object>();
        chartData.Add(new object[]
                        {
                        "UserId", "OrderNum"

                        });            
        chartData.Add(new object[]
                        {
                        "1", 3

                        });
        chartData.Add(new object[]
                        {
                        "2", 4

                        });
        chartData.Add(new object[]
                        {
                        "3", 6

                        });

        return Json(chartData);
    }
}

Startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //...

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Result:

enter image description here

Upvotes: 1

Related Questions