Thursday 28 June 2012

Call Page Method from JavaScript

Call Page Method from JavaScript



Write Page Method that You want to call (Method Must be Static):

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();
    }
}


Write JavaScipt to call Page Method :



    <script type=”text/javascript” language=”javascript”>
        function CallWebServiceMethod() {
        PageMethods.GetMenuItem(GetMenuItemComplete, errormethod);
        }

       function GetMenuItemComplete(val) {   /// Called When page method execute successfully
            $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”>
/// Bold written Attribute required for calling Page  method
    </asp:ScriptManager>
    <div id=”divItem”>
    </div>
    </form>
</body>

SESSION IN JAVASCRIPT


Session in Javascript



<script type=”text/javascript”>
 //To set Session
function Setsession() {
    if (window.sessionStorage) {
       sessionStorage.setItem(“key1″, document.getElementById(‘<%= Write.ClientID %>’).value);               
    }
}

//To get Session
 
function GetSession() {
     if (window.sessionStorage) {
         document.getElementById(‘<%= Get.ClientID %>’).value = sessionStorage.getItem(“key1″);
      }
}


</script>



To get Session Value using javascript

 <script type=”text/javascript”>
var session = '<%= Session["VALUE"] %>'; 

</script> 

Total Pageviews