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
-
Add using System.Web.Services;
in code-behind.
-
Method must be public static
.
-
Decorate method with [WebMethod]
.
-
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:
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:
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.