-1

I would like to know what url should we use on AJAX to call a WebMethod in an external C# class

To call a [WebMethod] on a page's code behind by AJAX we use:

url: 'default.aspx/Method'

But i am being unable to access a [WebMethod] in MyClass.cs (located in /foo/)

Those, for example, don't work:

url: 'default.aspx/MyClass.Method'
url: 'foo/MyClass.cs/Method'

How can i access a WebMethod on an external C# class file?

Tiago
  • 365
  • 1
  • 4
  • 17

1 Answers1

0

You need to add a web accessible file to interact with the external classes in order to access them from AJAX calls. You could use something like an asmx (ASP.Net web service) that exposes the webmethods. The file is basically just a markup place holder that points at a class file. Contents are just:

<%@ WebService Language="C#" CodeBehind="~/foo/MyClass.cs" Class="MyClass" %>

Then your class has to inherit from System.Web.Services.WebService and you should be good.

If you do an add file from Visual Studio and add a web service file you can get it to create all this for you.

  • Adding the Web Service via VS gives an asmx.cs with much more content. So this asmx should contain the WebMethods OR WebMethods pointing to Methods in the class? And your solution, is creating an empty .asmx and pasting that line? What is the AJAX url i should use to access the method according to your suggestion? – Tiago Jul 14 '16 at 10:05
  • Either add a file manually to point at your class or do what you did. Ideally you'd leave your business logic inside the class file as it is and use the asmx to expose the logic via webmethod even if the webmethod function is just `return MyClass.SomeFunction()`. To access it is just like you did for accessing an aspx. Set the url for your ajax call to `YourWebService.asmx/YourWebMethod`. – Charles Paske Jul 14 '16 at 14:49