In this article I will explain with example, how to make an AJAX call to ASP.Net WebMethod using jQuery.
Syntax
HTML Markup
The following HTML Markup consists of:
TextBox – For entering Name.
Button – For making AJAX call.
The Button has been assigned with a JavaScript onclick event handler.
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
Namespaces
You will need to import the following namespace.
C#
using System.Web.Services;
VB.Net
Imports System.Web.Services
Server Side Web Methods for Getting Current Time
The following WebMethod GetCurrentTime accepts username as a parameter.
Note: The method is declared as static (C#) and Shared (VB.Net) and is decorated with WebMethod attribute, unless you do this you won’t be able to call the methods using ASP.Net AJAX.
Inside the WebMethod, a greeting message with the current server time and string message is returned.
C#
[WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
VB.Net
<WebMethod>
Public Shared Function GetCurrentTime(ByVal name As String) As String
Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
DateTime.Now.ToString()
End Function
Client Side Script
When the Button is clicked, ShowCurrentTime function is executed.
Inside this function, an AJAX call is made to the GetCurrentTime method of ASP.Net WebMethod which accepts the username as parameter.
Finally, the response received from the WebMethod is displayed using JavaScript Alert Message Box in the Success event handler.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type ="text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: function(response) {
alert(response.responseText);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads