O'Reilly logo

Programming Atlas by Christian Wenz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Inline Web Service Methods

You have probably found that putting all the web methods for an application in a separate file is a bit cumbersome. From an architectural point of view, doing this seems like a good idea, but with simple scripts or applications (like most of the examples in this book), the extra .asmx file clutters up the project.

But with very little extra code, you can put all of your code in one place, namely in your main .aspx file (or its code-behind class file). This technique takes two steps. First, you have to import the web services namespace into the page file, using an @ Import directive:

<%@ Import Namespace="System.Web.Services" %>

Second, you need to put the code for the web method on your page. To identify it as a web service method (well, rather as a method that kind of works like a web method), use the [WebMethod] attribute as you would do in an .asmx file. Also note that the method must be declared as public:

<script runat="server">
  [WebMethod]
  publicfloat DivideNumbers(int a, int b)
  {
    if (b == 0)
    {
      throw new DivideByZeroException();
    }
    else
    {
      return (float)a / b;
    }
  }
</script>

Atlas automatically searches for all such methods and encapsulates them in the (client-side) PageMethods class. So to call the method, just use PageMethods.DivideNumbers():

function callService(f) {
  document.getElementById("c").innerHTML = "";
  PageMethods.DivideNumbers(
    parseInt(f.elements["a"].value),
    parseInt(f.elements["b"].value),
    callComplete,
    callTimeout,
    callError);
}

Since ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required