In this article I will explain with an example, how to call server side function using JavaScript in ASP.Net.
HTML Markup
The following HTML Markup consists of:
ScriptManager – It allows to call Server Side ASP.Net methods from client side without any PostBack using PageMethods. The EnablePageMethods property is set to True.
TextBox – For entering Name.
Button – For making AJAX call.
The Button has been assigned with a JavaScript onclick event handler.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
</div>
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 server using ASP.Net AJAX ScriptManager PageMethods and executes the GetCurrentTime method which accepts the username as a parameter.
Finally, the response is displayed using JavaScript Alert Message Box in the Success event handler.
<script type="text/javascript">
function ShowCurrentTime() {
PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</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