The PageMethods feature enables the using of code-behind page methods on the client side. This is easier and reliable to use and the main feature is it automatically validates the page parameters.
Page Method Example
ASPX <%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageMethods.aspx.cs" Inherits="PageMethods" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script type="text/javascript"> function AccessServerSide() { PageMethods.GetServerSideValue(onSuccess, onFailure); } function onSuccess(result) { alert(result); } function onFailure(error) { alert(error); } </script> </head> <body> <form id="form1" runat="server"> <div> <input type="button" value="Click Me" onclick="AccessServerSide()" /> <asp:ScriptManager ID="smPageMethods" runat="server" EnablePageMethods="true"></asp:ScriptManager> </div> </form> </body> </html>
Code Behind
using System; using System.Web.Services; public partial class PageMethods : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static string GetServerSideValue() { return "Yes I can access Server Side Code."; } }
Points To remember.
-The Page Method should be static using the attribute [WebMethod].
-The EnablePageMethods property of the script manger should be marked as “True”.
-The call back methods are mandatory to receive the processed result on the client side.