8

Possible Duplicate:
Call non-static method in server side(aspx.cs) from client side use javascript (aspx)

I have this following code that is working fine

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 question is if i want my WebMethod NOT to be static, how can i call it from JS?

[WebMethod]
public FooObj GetFooObj ()
{
    // some code that returns FooObj 
}
Community
  • 1
  • 1
user829174
  • 6,132
  • 24
  • 75
  • 125

3 Answers3

12

Not possible - PageMethods has to be static.

Reason is quite simple - a instance (non-static) method means it can access page state including controls. However, ASP.NET page/control model needs state information (view-state, event validation etc) for ensuring consistent state of controls. But in case of Page Methods, this is not possible because complete form is not posted back (which is essentially the idea behind PageMethods/ScriptServices - you send/receive only bare minimum information between client/server).

For using instance methods (assuming that you need control access), you should use UpdatePanel way of doing AJAX.

VinayC
  • 47,395
  • 5
  • 59
  • 72
3

The reason it supports only static methods is that page is instantiation is not done, if you want to use non static web methods then go for web service(.asmx).

AshokD
  • 442
  • 4
  • 14
0

Why not implementing a simple web service? you can find a really good example from here

ravisilva
  • 259
  • 3
  • 10