0
Answer

How WebMethod works in ASP.NET C# with both PageMethods and jQuery AJA

Photo of Sandhiya Priya

Sandhiya Priya

15h
87
1

 What is a WebMethod?

  • A WebMethod is a static method in the ASP.NET code-behind, decorated with the [WebMethod] attribute.

  • It exposes server-side logic so client-side code (JavaScript, jQuery, AJAX) can call it directly.

  • Useful for partial page updates (e.g., saving data, checking username availability, fetching records).

 Requirements

  1. Add using System.Web.Services; in code-behind.

  2. Method must be public static.

  3. Decorate method with [WebMethod].

  4. Call it using PageMethods or jQuery AJAX.

 Example 1: Simple WebMethod returning string

Code-behind (Default.aspx.cs):

using System;

using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
    [WebMethod]
    public static string GetMessage(string name)
    {
        return "Hello, " + name + "! This is from server.";
    }
}

 

Client-side (Default.aspx):

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

<input type="text" id="txtName" />
<button onclick="callWebMethod()">Call WebMethod</button>
<p id="result"></p>

<script type="text/javascript">
    function callWebMethod() {
        var name = document.getElementById("txtName").value;
        PageMethods.GetMessage(name, onSuccess, onError);
    }
    function onSuccess(response) {
        document.getElementById("result").innerText = response;
    }
    function onError(err) {
        alert("Error: " + err.get_message());
    }
</script>

 

 How it works:

  • User types a name → clicks button → PageMethods.GetMessage() calls the server → returns greeting → shown on the page.

 Example 2: Using jQuery AJAX to call WebMethod

Code-behind (Default.aspx.cs):

using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
    [WebMethod]
    public static string GetServerTime()
    {
        return DateTime.Now.ToString();
    }
}

 

Client-side (Default.aspx):

<script src="jquery-3.6.0.min.js"></script>

<button onclick="getTime()">Get Server Time</button>
<p id="timeResult"></p>

<script type="text/javascript">
    function getTime() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetServerTime",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                $("#timeResult").text("Server Time: " + response.d);
            },
            error: function (xhr, status, error) {
                alert("Error: " + error);
            }
        });
    }
</script>

 

 How it works:

  • Button click triggers AJAX call → hits GetServerTime() → returns current server time → updates UI without reloading the page.

 Common Uses of WebMethod

  • Check if username/email already exists.

  • Fetch data without refreshing the page.

  • Insert/update database records via AJAX.

  • Validate inputs server-side instantly.

Answers (0)