WebMethod Example
I want a label box to be refreshed every one second with a random number generated at the server
This is a classic example of WebMethods. WebMethods are written on the server side in the page class. WebMethods are static. Here is a simple implementation of a webmethod:
private static Random random = new Random(1000); [WebMethod] public static int GetRandomNumber() { return random.Next(10, 99); }
To be able to call this WebMethod from Javascript, the asp:ScriptManager should have the EnablePageMethods property set to true:
<form id="form1" runat="server"> <asp:ScriptManager runat="server" EnablePageMethods="true"></asp:ScriptManager> <asp:Label ID="Random" runat="server"></asp:Label> </form>
From Javascript, the WebMethod can be called using the syntax PageMethods.FunctionName(Arg0, Arg1, OnSucceededCallBack); WebMethods are executed asynchronously. So a callback function has to be provided. Here is an example of updating a label box with the random number
<script type="text/javascript"> setTimeout("PageMethods.GetRandomNumber(setRandom);", 1000); function setRandom(result) { document.getElementById("Random").innerText = result; setTimeout("PageMethods.GetRandomNumber(setRandom);", 1000); } </script>
Posted by Vijay on 07-Oct-2009 10:27 AM
Category : ASP.NET AJAX
Category : ASP.NET AJAX



its not working please give any other example of ajax web method.