0

Currently I am writing a web app to pull data from a database and display it dynamically using google charts. When I start the website I am alerted with an error when trying to post and am left with this error message:

Error

This is my Code:

Here is the .aspx file:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="GoogleChart.aspx.cs" Inherits="GoogleChartsWebForm.GoogleChart" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
    <script src="Scripts/jquery-3.3.1.js"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>

    <script>
        var chartData; //Global Var For Data
        google.load("visualization", "1", { packages: ["corechart"]});

        //Fill Chart Data



        $(Document).ready(function () {
            $.ajax({
                url: "GoogleChart.aspx/GetChartData",
                data: "",
                dataType: "json",
                type: "POST",
                contentType: "application/json; chartset=utf-8",
                success: function (data) {
                    chartData = data.d;
                },
                error: function () {
                    alert("Error loading Data! Please Try again!");
                }
            }).done(function () {
                //after complete loading data
                drawChart();
            });
        });


        function drawChart() {
            var data = google.visualzation.arrayToDataTable(chartData);

            var options = {
                title: "Chart",
                pointSize: 5
            };
            var lineChart = new google.visualization.LineChart(document.getElementById('chart_div'));
            lineChart.draw(data, options);
        }

    </script>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <div id="chart_div" style="width: 800px; height: 400px;">
        <%-- GoogleCharts WebForm Will Load Here --%>
    </div>
</asp:Content>

And here is the .aspx.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GoogleChartsWebForm
{
    public partial class GoogleChart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static object[] GetChartData()
        {
            List<Table> data = new List<Table>();
            //Here DB ENTITY is our DB context
            using(DataBaseEntities dc = new DataBaseEntities())
            {
                data = dc.Tables.ToList();
            }
            var chartData = new object[data.Count + 1];
            chartData[0] = new object[]
            {
                "Month",
                "TotalSales"
            };

            int j = 0;
            foreach (var i in data)
            {
                j++;
                chartData[j] = new object[] { i.Month, i.TotalSales };
            }
            return chartData;
        }
    }
}

I don't see anything that would be wrong with this. I am thinking that the error may be when it is trying to access the database. I am fairly new to ASP.Net so am coming to you guy for some answers. Excuse me if this may seem to broad of a question.

mason
  • 31,774
  • 10
  • 77
  • 121
  • It looks like you're setting up a web service? Is that what you want or would an ASP.NET MVC controller be more appropriate? In any case the 401 from the jQuery is a HTTP status code meaning unauthorised, i.e. not at the database level but at the code/page/method level. – Neil Billingham Jun 22 '18 at 14:33
  • Any idea why it would be unauthorized? –  Jun 22 '18 at 14:40
  • It will be unauthorised because that webservice required authorisation, and you haven't supplied any credentials in the request to allow the server to do authentication or authorisation. does your application use Windows Authentication by any chance? If so then you need to send your Kerberos token along with the ajax request. A regular browser request does this automatically but for AJAX you need to specify it. in jQuery ajax you can specify `xhrFields: { withCredentials: true }` in the ajax options – ADyson Jun 22 '18 at 14:47
  • If you use something else such as a token-based system e.g OAuth, or Basic Authentication, then supply those credentials instead. You can easily search for how to do that using jQuery ajax – ADyson Jun 22 '18 at 14:47
  • It looks a bit mixed up to me to be honest. The System.Web.UI.Page is all about dishing out html pages and excepts a postback from html
    s - at least that's how I've used them. Your jQuery post might be better handled using ASP.NET Web API 2.
    – Neil Billingham Jun 22 '18 at 14:47
  • 1
    @NeilBillingham The method is decorated with the WebMethod attribute which is used commonly in ASP.NET Forms applications to enable a method to be accessed directly as an endpoint, it allows people to quickly create a kind of ad-hoc API for the odd AJAX call they might want. Not beautiful design but that's what it does. If OP wanted to use MVC or Web API controllers they'd have to create a whole new project, because this is a Forms project already – ADyson Jun 22 '18 at 14:49
  • It is using Windows Auth. I will try and sending the token with the request. –  Jun 22 '18 at 14:50

1 Answers1

0

To fix this I simply did this:

Inside ~/App_Start/RouteConfig.cs change:

settings.AutoRedirectMode = RedirectMode.Permanent;

To:

settings.AutoRedirectMode = RedirectMode.Off;

Source: https://stackoverflow.com/a/23037758/9962623

  • Interesting, this would seem to have little to do with 401 errors on the face of it. Is there more to it than you have mentioned? – ADyson Jun 22 '18 at 15:42
  • Nope, nothing more. I tried sending the tokens along with ajax and was still getting the same error. I got the answer from this source: https://stackoverflow.com/a/23037758/9962623 –  Jun 22 '18 at 15:48