Skip to Main Content
Programming Atlas
book

Programming Atlas

by Christian Wenz
September 2006
Intermediate to advanced content levelIntermediate to advanced
408 pages
10h 38m
English
O'Reilly Media, Inc.
Content preview from Programming Atlas

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Go Systems Programming

Go Systems Programming

Mihalis Tsoukalos

Publisher Resources

ISBN: 0596526725Supplemental ContentCatalog PageErrata