The web method within the aspx page is failing to execute

On page load, I am attempting to make an ajax request using the AngularJS $http service to fetch JSON data from a web method located in my User.aspx.cs page.

The web method is defined as follows:

[WebMethod]
    [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
    public static List<Users> GetUsers()
    {
        DBUtil objUtils = new DBUtil(); //This class handles database connections

        List<Users> list = new List<Users>();
        string strQuery = "select * from TM_Users";
        DataTable dt = objUtils.GetDataTable(strQuery);
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            list.Add(new Users {
                FullName=dt.Rows[i]["FullName"].ToString(),
                UserName=dt.Rows[i]["UserName"].ToString(),
                Password=dt.Rows[i]["Password"].ToString(),
                phNum=dt.Rows[i]["MobileNo"].ToString(),
                EmailId=dt.Rows[i]["EmailAddress"].ToString(),
                Usertype=dt.Rows[i]["UserType"].ToString(),
                CenterId=dt.Rows[i]["HealthCenterID"].ToString()
            });
        }
        return list;
    }

The issue arises when trying to call the web method within a controller defined in a separate JavaScript file named Control.js. The objective is to populate an ng grid with data retrieved from the database. Below is the code snippet:

var app = angular.module("myApp", ["ngGrid"]);

app.controller('myCtrl', function ($scope, $http, $location) {
    $scope.location = $location;
    var url1 = "User.aspx/GetUsers";
    var myData;
    $http.get(url1).success(function (data,status,headers) {
        myData = data;
    }).error(function (err) {
        console.log(err);
    })
    $scope.gridOptions = {
        data: 'myData'
    };

});

Upon debugging, it was observed that the success handler executes successfully. However, the web method on the aspx.cs page does not execute as expected. Instead, the response received in the success handler's data is the entire HTML content of the web page.

Any assistance or insights would be highly appreciated!

Answer №1

To improve your http get call, make the following adjustments. Include the content type, an empty data object, and set the response type to json.

var app = angular.module("myApp", ["ngGrid"]);

app.controller('myCtrl', function ($scope, $http, $location) {
    var request =
    {        
    method: "GET",
    url: "User.aspx/GetUsers",
    data: {},
    headers: { "Content-Type": "application/json" },
    responseType: 'json'
    }

    $http(request).then(function (data,status,headers) {
        myData = data;
    }).error(function (err) {
        console.log(err);
    })
    $scope.gridOptions = {
        data: 'myData'
    };

});

});

Answer №2

Always make sure the Webmethod is declared as a static method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain information from YouTube and format it into a list item

Currently, I'm working on compiling a list of videos that includes the title, link, image, and creator of each video. It's been a bit challenging :S <script type="text/javascript"> $(document).ready(function(){ $.getJSON('http://gdata ...

Display a toolbar underneath text that has been selected using jQuery

I am attempting to display a toolbar underneath selected text once the user has made a selection. After exploring various Stack Overflow responses, I have devised the following code. My goal is for the toolbar to activate when a user selects text not only ...

Enhance Canvas when React State Changes

I am currently working on integrating a canvas into my React project. The main goal is to overlay styled text (with custom font color, style, and size) on an image. I've set up a basic form to input the styling attributes and the desired text. Whenev ...

Issues with date clicking on FullCalendar in Angular

I'm currently using version 4.4.0 of the FullCalendar plugin, but I am facing an issue where the dayClick event is not being triggered in my code. Below is a snippet of my code: calendar.component.html <full-calendar defaultView="dayGridMonth ...

Sharing data between nested ng-repeat in Angular can be achieved by utilizing scope inheritance

I am currently experiencing an issue with a nested ng-repeat structure. Below is a snippet of my sample HTML code. I need to determine the number of rows with the id "thirdNg" (number_of_thirdNg_row) after applying a filter to the parent3 ng-repeat with ...

Angular: Unable to access values of non-existent data (reading '0')

I'm encountering an error when trying to import an excel file using the following code Angular Ag Grid Excel Import Cannot read properties of undefined (reading '0') I'm attempting to import a file named Book.csv, and wondering if thi ...

Securing Codeigniter with CSRF protection while using datatables and an AJAX URL

I am currently utilizing codeigniter and have implemented CSRF protection. We have enabled it using the following configuration: $config['csrf_protection'] = TRUE; For form submission, we are using the following code: `<input type="hidden" ...

Angular BehaviorSubject is failing to emit the next value

I am facing an issue with a service that uses a Behavior subject which is not triggering the next() function. Upon checking, I can see that the method is being called as the response is logged in the console. errorSubject = new BehaviorSubject<any> ...

Picking specific <button> items

Presented here are a series of buttons to choose from: <button id="hdfs-test" type="button" class="btn btn-default btn-lg">HDFS</button> <button id="hive-test" type="button" class="btn btn-default btn-lg">HIVE</button> <button id ...

Retrieve information from the NodeJs server pertaining to the previous 10-minute timeframe

While working on a project where I needed to fetch and display data from a website within the past 10 minutes that meets a certain condition, I initially thought of storing it in a global variable. However, I realize that this may not be the best practice. ...

Troubleshooting Issue with Filtering Nested Object Array Based on Property

At the core of my data structure lies an array of orders, each containing an array of line items. These line items, in turn, are associated with their respective categories. I am currently attempting to filter the order array based on the category ID of th ...

Using class binding for both ternary and non-ternary attributes

Suppose we have a tag that utilizes a ternary operator to apply alignment: <td :class="alignment ? ('u-' + alignment) : null" > This functions as intended since the pre-defined alignment classes are in place, now if we want to ...

Unable to locate a compatible version for require-from-string with the specified version range of ^1.1.0

Needed Packages for npm Project: "dependencies": { "angular-chart.js": "1.1.0", "angular-cookies": "1.5.7", "angular-ui-bootstrap": "2.4.0", "angular-ui-grid": "4.0.5", "checklist-model": "0.10.0", "json-schema": "0.2.2" } Howev ...

Accessing the current clicked item in $scope using an Angular Directive within ng-repeat

I have set up a custom directive called calendar which includes a date picker created in JQuery. To associate the ng-model with the date picker, I am using the following code successfully: var clickedID = "#" + $scope.indexid + "_datePicker"; $(clickedID ...

Struggling to locate the element value in Puppeteer? Reach out for assistance with await page.waitForSelector() or await page.waitForXPath()

insert image description here[ await page.waitForSelector('.DateRangeSelectorstyles__DateInput-sc-5md5uc-2.kXffji.sc-cSHVUG.VGFsW'); await page.type('.DateRangeSelectorstyles__DateInput-sc-5md5uc-2.kXffji.sc-cSHVUG.VGFsW','01- ...

What could be the issue with my JSON data stream?

Trying to set up the Fullcalendar JQuery plugin with a JSON feed has been a bit of a challenge. The example provided with the plugin works perfectly, so it seems like there might be an issue with my own feed. Here is the output from the working example JS ...

Implementing a for loop within a scrolling function

How do I multiply functions inside the scroll loop? This is what I currently have: $(window).scroll(function() { b1Center = $("#block-1").offset().top - ($(window).height() - divHeight) / 2; b1Bottom = $("#block-1").offset().top - $(window).height(); b1T ...

Displaying svg files conditionally in a react native application

I have developed an app specifically for trading dogs. Each dog breed in my app is associated with its own unique svg file, which are all stored in the assets folder (approximately 150 svg files in total). When retrieving post data from the backend, I re ...

What is the best way to append something to the textContent property of an HTML tag within a markup page?

While working on resolving an XSS vulnerability in the jqxGrid where the cell content is rendered as HTML, I encountered a scenario like this: <a href="javascript:alert('test');">Hello</a>. To address this issue, I am exploring ways t ...

Puzzled by the unexpected error I encountered while using Node.js (require.js)

My script was running smoothly until I encountered a sudden error: undefined:3 <!DOCTYPE html> ^ SyntaxError: Unexpected token < at Object.parse (native) at Request._callback (C:\Users\Tom\Pictures&bso ...