Category:
ASP.Net Ajax
In my previous posts about ASP.Net Ajax I wrote about how to call a Web Service from client-side code. I also write for a long time ago a post about Client-side postback. Both methods can be used to call a server-side method from client-side scripts. In this post I’m going to write about another way of calling a server-side method from client-side script with ASP.Net Ajax.
If you don’t want to create a Web Service to make it possible to call server-side code from client-side script, you can add a static method to the “code-behind” of your page. This method can be callable from client-side script in an easy way. What you first need to do is to mark it as a WebMethod to expose the method (make sure to import the System.Web.Services namespace):
[WebMethod]
public static string Hello(string value)
{
return value;
}
When this is done you need to enable page method calls, this can be done by setting the EnablePageMethods attribute of the ScriptManager to true:
<asp:ScriptManager ID="scriptManager" EnablePageMethods="true" runat="server" >
When you call a WebService you needed to add a reference to the WebService, but in this case when you want to call a WebMethod that is located in the “code-behind” of your page, you only need to enable the use of page methods.
To call a Web Service or a page method is very similar. When you call the method you can specify a client-side callback method. The value returned from the page method will be passes as an argument to the specified client-side callback method:
<script type="text/javascript">
function CallMyPageMethod()
{
PageMethods.Hello(“Hello to you!”, OnSucceeded);
}
function OnSucceeded(result)
{
alert(result);
}
</script>
Note: To call your page methods from client-side script you need to use the PageMethods class.
This is all you need to do, so happy coding!
|