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

The Vue property or method is unrecognized when utilizing the non-minified version

When I attempted to display the name 'John' using an inline template in a simple Vue example, I encountered the following error message: [Vue warn]: Property or method "name" is not defined on the instance but referenced during render. ...

Transforming a flow type React component into JSX - React protocol

I have been searching for a tooltip component that is accessible in React and stumbled upon React Tooltip. It is originally written in flow, but I am using jsx in my project. I am trying to convert the syntax to jsx, but I'm facing difficulties with t ...

Mastering the Art of jQuery: Easily Choosing and Concealing a Div Element

I'm currently facing challenges in removing a div upon successful AJAX completion. The issue I'm encountering is that the word "Added" appears twice after success, indicating that I am not properly selecting the two divs containing it. Any sugges ...

Sending multiple values with the same name via AJAX using PHP

I'm facing an issue with my code: <form method="post" id="result-image" name="result-image" action="" > <?php $i=1; foreach ($data as $key => $datas) { ?> <div class="col-md-2 thumb custom-size col-lg-3 col-xs-4"> ...

Switching on and off a class in Next.js

I'm a beginner with Next.js and React framework. My question is regarding toggling a class. Here's my attempt in plain JS: function toggleNav() { var element = document.getElementById("nav"); element.classList.toggle("hidde ...

Steps for inserting a script tag in an Angular component

My Angular/Typescript website needs to integrate a third-party script that generates a table. However, I'm facing issues with rendering the table within the home.component.html file. I've managed to embed the script, but it doesn't seem to ...

user input not displayed within md-autocomplete

I'm currently incorporating angular material's autocomplete component into my website. Within the html code, I have the following: <md-autocomplete md-selected-item="selectedItem" md-search-text="searchText" md-items="item in getMatches ...

The animated loading image is taking an eternity to actually load

My website is loaded with heavy front-end features and I'm using a loading gif to help with the loading process. However, I've noticed that in Safari, there is a delay before the gif loads after the background does, which takes away from the inte ...

Getting data from an API using a Bearer Token with React Hooks

I am currently developing a React application that is responsible for fetching data from an API. This API requires Bearer Token Authorization. To handle this, I have implemented useState() hooks for both the token and the requested object. Additionally, th ...

Can a link be generated that swaps out the original URL redirect for the following visitor upon clicking?

Can the program be fed with a list of links to automatically redirect to the next URL once clicked? In this setup, each visitor would only see one link and not have access to any other URLs in the chain. Is there a way to make this happen? Any suggestion ...

Placing the video at the center of the background image

                    Can someone assist me with a design issue I'm facing? I have two divs within a section. The left div contains a heading and a button, while the right div contains a video. However, when I try to add a background image to ...

Issue - The module ./en.json could not be located when using the vue-i18n plugin

I recently integrated the i18n plugin into my existing Vue project to add localization. After following all the installation instructions from various sources (such as here), I made sure that each locale has its own file under /src/locales with the correct ...

Is it possible to track traffic using Alexa or SimilarWeb on a single-page application?

We are currently grappling with the challenge of how to effectively track traffic and user engagement within our classified sites on a single-page application built in angularJS. While we have successfully managed SEO and tracking with Google Analytics, we ...

What is the best method to consistently convert a deeply nested object into a tabular format that can be easily reversed

Imagine having a deeply nested object with an unknown structure until runtime, like: { "row-0" : { "rec-0" : { "date" : 20220121, "tags" : [ "val-0" ] }, ...

Trigger the click event on a specific class selector to extract the corresponding ID

I have an HTML Table with each row: <table> <tr><td><a href='#' id='1' class='delete'>delete</a></td></tr> <tr><td><a href='#' id='2' class='de ...

Encountering a npm error E404 when trying to install unicons package for React development

I recently started working on a weather app project using create-react-app and encountered an issue while trying to install unicons for the project. Despite attempting a few solutions, I was unable to resolve the problem. Here is the command I used for th ...

Can you extract debugging details from an ajax preflight inquiry?

I am currently working on a JavaScript project that involves making an AJAX request. However, I am encountering issues with the preflight OPTIONS call for this request failing. To provide some transparency to the user, I would like to display debug infor ...

Access another key within an object

Here's a code snippet from my module: exports.yeah = { hallo: { shine: "was", yum: this.hallo.shine } } In the above code, I'm attempting to reference the shine property in yum: this.hallo.shine However, when I run the script, ...

There was an issue when trying to process the Javascript data structure with JSON.parse

Currently, I have the following data stored in a JavaScript variable: "{'Headings': [{'name': 'Behavior', 'majorTopic': 'N', 'vote': {'down': 1, 'up': 1}}, {'na ...

What is causing the consistent error message "unable to read property 'logged' of undefined"?

Here is the code snippet from my app.js: var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie- ...