Using AJAX in JavaScript to call a webmethod in ASP.NET that is not static

Similar Question:
Executing non-static method in aspx.cs from client side using javascript (aspx)

The code snippet below is currently functioning correctly

function getFooObj() {
    $.ajax({
        type: "POST",
        url: "Dummy.aspx/GetFooObj",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
           alert('good');
        }
    });
}

[WebMethod]
public static FooObj GetFooObj ()
{
    // some code that returns FooObj 
}

My query pertains to making my WebMethod NOT static and how I can then access it from JavaScript?

[WebMethod]
public FooObj GetFooObj ()
{
    // some code that returns FooObj 
}

Answer №1

Unfortunately, PageMethods must be declared as static.

The reason for this requirement is that non-static methods have access to page state and controls. However, ASP.NET's page/control model relies on state information (view-state, event validation, etc.) to maintain the consistency of controls. Since Page Methods do not trigger a complete form postback (which is the core concept behind PageMethods/ScriptServices - transmitting only essential data between client/server), it is not possible to use instance methods in this context

If you still need control access while using AJAX, consider implementing UpdatePanel instead.

Answer №2

The support for only static methods can be attributed to the lack of page instantiation. If you require non-static web methods, it is advisable to utilize a web service (.asmx).

Answer №3

Have you considered creating a basic web service? An excellent sample can be found at this link

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

Patience is key when awaiting the completion of several promises

I am currently utilizing the SQLStorage feature provided by the Ionic platform. The remove function within this tool returns a promise. Within my code, I have a need to remove multiple values and then execute some additional code once all removals are comp ...

Struggling to extract information from a serialized Python object using JavaScript/jQuery?

Continuing the previous issue with an AJAX call to a Django view (restframework endpoint), the problem has now shifted to the frontend. $.ajax({ url: '/notify/', type:'GET', dataType: '', success: function (da ...

unable to use ref to scroll to bottom

Can someone explain to me why the scroll to bottom feature using ref is not functioning properly in my code below? class myComponent extends Component { componentDidMount() { console.log('test') // it did triggered this.cont ...

What is the reason behind child state resolve functions being executed prior to the parent state promises being resolved?

I am currently utilizing ui-router version 0.2.13. According to this page: All resolves on one state will be resolved before moving on to the next state, even if they aren't injected into that child Additionally, all resolves for all the states ...

Show/hide functionality for 3 input fields based on radio button selection

I need assistance with a form that involves 2 radio buttons. When one radio button is selected, I want to display 3 text boxes and hide them when the other radio button is chosen. Below is the code snippet: These are the 2 radio buttons: <input type= ...

Change the location of an html td element with JavaScript

I am currently working on a simple JavaScript car racing game where the cars are represented by HTML table elements. I want to implement functionality where pressing the "e" key moves player one's car and the "d" key moves player two's car. This ...

How can we incorporate SaxonJS higher-order functions into the Node.js runtime, separate from JS/HTML?

We are currently in the process of transitioning an older C# system that relied on custom functions to enhance XSLT processing. Our plan is to convert it to Node.js/saxon-js. After reviewing the documentation, it appears that while higher order functions ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

Encountered an issue loading a resource due to a lost network connection while using Safari 9 and JBoss WildFly 8.2

After successfully deploying my War file to the JBoss Wildfly 8.2 server, I attempted to access the application link from a remote MAC machine. The application opened correctly, but some functionalities were not working properly. An error message popped u ...

What is the best way to retrieve the number of clients in a room using socket.io?

I am using socket.io version 1.3.5 My objective is to retrieve the number of clients in a specific room. This is the code implementation I have: socket.on('create or join', function (numClients, room) { socket.join(room); }); ...

Having difficulty with the useState hook in a material ui functional component that integrates with Firebase

Currently, I am endeavoring to create a sign-up form utilizing a Material UI functional component. Within this form, I am aiming to trigger a signup event by using the "onClick" attribute attached to the sign-up button. My approach involves passing the ema ...

Exploration Pointers for Foursquare Web Users

Why does my search suggestion keep returning '568 broadway' even after I have updated the authentication to my client id and client secret? Currently running on: https://api.foursquare.com/v2/venues/suggestCompletion?ll=40.7,-74&query=fours ...

What is the best way to generate multiple progress bars by leveraging a for loop?

Exploring the code snippet below, I've been creating a progress bar that reacts to specific data input in array form. However, the issue I've encountered is that the code only generates a single progress bar. How can I incorporate this into my f ...

Steps to display a div element periodically at set time intervals

I've created a user greeting message that changes based on the time of day - saying Good Morning, Good Afternoon, or Good Evening. It's working well, but I'm wondering how I can make the message hide after it shows once until the next part o ...

Three.js: Create a Custom Cube Panorama with Adjustable Orientation (Front, Back, Left, Right, etc.)

For my project, I am implementing a rotating cube panorama image with 6 sides: Check out the example here View the code on GitHub scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 90, window.innerWidth / window.innerHeight, 0.1, 100 ); cam ...

Retrieve the selected value from a radio button

I am attempting to display the chosen value in an input field when a radio button is selected. However, the functionality seems to be broken when I include bootstrap.min.js. You can find the code on JSFiddle. $('input:radio').click(function() ...

Incorporating the values of JavaScript objects into a global variable

I'm currently developing a bank account program and facing a challenge in adding my direct debits (DDs) into the global variable. When I create new objects using my constructor function and add them into the bank account, only the last created DD is s ...

Is there a better option than using public methods when transitioning from class-based to function-based React components?

When working with React components that utilize hooks, they must be function-based rather than class-based. I've encountered a challenge transitioning from calling methods on child components in class-based components to achieving the same functionali ...

Applying the jqtransform plugin to all forms except for one

We've implemented the jQuery jqtransform plugin to enhance the appearance of our website's forms. However, there is one particular form that we'd like to exclude from this transformation. I made adjustments to the script that applies jqtrans ...

Expanding a JSON data structure into a list of items

In my Angular service script, I am fetching customer data from a MongoDB database using Django: getConsumersMongodb(): Observable<any> { return this.httpClient.get(`${this.baseMongodbApiUrl}`); } The returned dictionary looks like this: { &q ...