Calling Page Method [.AJAX]
In this blog post, we will learn how to call a method existing on a page using Ajax.
First of all, the method should have the WebMethod attribute and should be static.
[System.Web.Services.WebMethod]
public static string GetServerTime()
{
return DateTime.Now.ToString();
}
The above method will return the date time on the server.
Second, You should add the EnablePageMethods="true" attribute to the ScriptManager control to allow calling a page method.
Now on client pageload event we will call the method on the server which will return a string containing the date time and display it on a textbox inside an UpdatePanel Control
<script language="javascript">
function pageLoad(sender, eventArgs)
{
getTime();
}
function getTime()
{
// call the method on the server and wait till the code has completed its execution
PageMethods.GetServerTime(OnGetServerTimeComplete)
}
function OnGetServerTimeComplete(result, userContext, methodName)
{
// Get the textbox inside the UpdatePanel Control
var textbox = $get('<%=txtDateTime.ClientID%>');
// Set the result into the textbox
textbox.value = result;
}
</script>
Hope this Helps,