Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Asynchronous Invocation of Web Services and Page Methods in ASP.NET AJAX

Tech May 7 3

Invoking Web Services

Web Services are elevated to a primary role in ASP.NET AJAX because they are inherently designed to encapsulate business logic. By lacking a user interface and focusing purely on logic, Web Services align perfectly with the ASP.NET AJAX philosophy of strictly separating the presentation layer from the business logic layer. In this model, the client-side framework handles user interaction and UI updates, while the server side provides raw data without any presentation styling.

Through the client proxy automatically generated by the ASP.NET AJAX communication layer, calling Web Services from JavaScript to retrieve data is remarkably straightforward. Let's examine this process with a simple example where the user inputs a name, and the application retrieves a greeting message from the server asynchronously.

Server-Side Web Service Implementation

First, create a Web Service named GreetingService. Define a standard web method, GreetUser, which accepts a name string and returns a formatted greeting.

using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class GreetingService : WebService
{
    [WebMethod]
    public string GreetUser(string userName)
    {
        return $"Greetings, {userName}!";
    }
}

The addition of the [ScriptService] attribute is critical. It instructs the ASP.NET AJAX framework to generate a JavaScript proxy for this service, enabling client-side invocation. Ensure the System.Web.Script.Services namespace is included.

Client-Side Configuration and Invocation

On the ASP.NET page, add a ScriptManager control. This component is required to manage client scripts and register the Web Service reference.

<asp:ScriptManager ID="scriptManager" runat="server">
    <Services>
        <asp:ServiceReference Path="Services/GreetingService.asmx" />
    </Services>
</asp:ScriptManager>

Next, define the user interface elements: a text box for input, a button to trigger the call, and a container for the result.

<input id="nameInput" type="text" />
<input id="invokeButton" type="button" value="Get Greeting" 
    onclick="handleButtonClick()" />
<div id="displayArea"></div>

The JavaScript logic retrieves the input and calls the server method via the generated proxy. Note that the method signature mirrors the server-side definition, with an additional parameter for the callback function that handles the response.

function handleButtonClick() {
    var userInput = $get("nameInput").value;
    GreetingService.GreetUser(userInput, onGreetingSuccess);
}

function onGreetingSuccess(response) {
    $get("displayArea").innerHTML = response;
}

In this example, onGreetingSuccess is the callback that executes once the server response is received. The framework automatically passes the Web Service's return value to this function.

Invoking Page Methods

While using dedicated Web Services is the recommended approach for architectural purity, ASP.NET AJAX also supports calling static methods defined directly within the code-behind of the current page. This feature is particularly useful for quick implementations or when refactoring legacy applications where moving logic to a separate service file is impractical.

Defining the Page Method

To expose a page method to the client, it must be public, static, and decorated with the [WebMethod] attribute.

[WebMethod]
public static string GetPageGreeting(string visitorName)
{
    return $"Welcome, {visitorName}!";
}

Client-Side Configuration

The ScriptManager must have its EnablePageMethods attribute set to true to generate the necessary proxies for methods located in the current page.

<asp:ScriptManager ID="scriptManager" EnablePageMethods="true" runat="server" />

The HTML structure remains similar to the previous example:

<input id="visitorInput" type="text" />
<input id="invokePageBtn" type="button" value="Invoke Page Method" 
    onclick="triggerPageCall()" />
<div id="resultOutput"></div>

Calling the Method via JavaScript

Client-side invocation of page methods uses the PageMethods proxy object. The syntax follows the pattern PageMethods.MethodName(params, callback).

function triggerPageCall() {
    var name = $get("visitorInput").value;
    PageMethods.GetPageGreeting(name, onPageCallSuccess);
}

function onPageCallSuccess(result) {
    $get("resultOutput").innerHTML = result;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.