Thursday, 24 May 2012

Call Page Method from JavaScript


public partial class PageMethod : System.Web.UI.Page
{
   [System.Web.Services.WebMethod()]
    public static string GetMenuItem()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<ul>");
        sb.AppendFormat("<li>{0}</li>","First");
        sb.AppendFormat("<li>{0}</li>", "Second");
        sb.AppendFormat("<li>{0}</li>", "Third");
        sb.AppendFormat("<li>{0}</li>", "Forth");
        sb.AppendFormat("<li>{0}</li>", "Fifth");
        sb.Append("</ul>");
        return sb.ToString();
    }
}


JavaScript to call Page Method :

<script type="text/javascript" language="javascript">
        function CallWebServiceMethod() {
       
        //To pass parapeters with methos write parameters values before Complete
           and error method

        PageMethods.GetMenuItem(GetMenuItemComplete, errormethod);
        }

      // Called When page method execute successfully
       function GetMenuItemComplete(val) {          
          $get(“divItem”).innerHTML = val;
        }

        function errormethod(val) {    //  called when error occurs in execution
        alert(“Error” + val)
        }
    </script>


At last Write HTML for display result :

<body onload=”CallWebServiceMethod();”>
    <form id=”form1″ runat=”server”>
    <asp:ScriptManager ID=”ScriptManager1″ EnablePageMethods=”true” runat=”server”>
    </asp:ScriptManager>
    <div id=”divItem”>
    </div>
    </form>
</body>

EnablePageMethods=”true”   Attribute required for calling Page  method

No comments:

Post a comment