10.2. Inline Web Service MethodsYou 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 we only want to use the inline web services functionality of Atlas, we can run Atlas in Runtime Mode by setting EnableScriptComponents to "false". Example 10-3 shows the complete code for an ASP.NET page in which both the page code and the web service method code is in one file. Example 10-3. Web service code and Atlas code together in one file
Figure 10-2 shows the results that are displayed when you load the page, enter two numbers, and click the Divide Numbers button. Figure 10-2. One file, one web service, one division operation |