2

I can get this to work if I have the c# [WebMethod] code in the default aspx.cs file but I cannot get it to work for a separate c# file I get a "webmethods undefined".

I have the script manager set to EnablePageMehods = true.

My separate class looks like this

public class TestClass
{

    [WebMethod]
    public static string Test()
    {
        string a = "Hello Worlds";
        return a;
    }

}

The JS looks like this

function testwebmethod() {
       PageMethods.Test(onSucceed, onError);
   }
   function onSucceed(result) {
       alert(result);
   }
   function onError(result) {
   }

I have tried inhereting from System.Web.UI.Page as it works in defualt cs file but this still had no avil.

Thanks in advance

Christian Strempfer
  • 7,291
  • 6
  • 50
  • 75
SammyG
  • 299
  • 1
  • 4
  • 15

1 Answers1

2

The WebMethod attribute only makes a method callable from the client-side when specified in two locations: ASPX code behind files and ASMX web-service code-behind files. Any other place and it does not have any impact.

On ASPX pages, it's meant to define web accessible methods that are only applicable to that given page. On ASMX web services, its meant to gather like functionality together and make it accessible by all pages. (Conceptually, once you define the end-points, you can do whatever you want from the client as long as you know where the URLS are..)

If you want to make a separate class for all your AJAX server side calls, add an ASMX Web Service to your project and call that. You can look at this SO post: Calling ASMX Web Service from Javascript for more information.

The reason why inheriting from System.Web.UI.Page does not work is because you need to have a ASPX declarative page to point to the given Page-derived class before ASP.NET understands how to route web requests to it.

Community
  • 1
  • 1
syazdani
  • 4,760
  • 1
  • 26
  • 35