Thursday, June 17, 2010

How to access Page Method using Script Manager - Asp.net

Demo:
Using asp.net ScriptManger setting EnablePageMethods=true we can access WebMethods
  1. Method should be static
  2. Set ScriptManager EnablePageMethods=true
  3. Use java script PageMethods.CheckUserName(value, OnSucceeded, OnFailed);
  4. OnSucceeded - function to executed on success
  5. OnFailed - function to executed on fail
Please see the example below
<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <title></title>
    <script runat="server">
        [System.Web.Services.WebMethod]
        public static string CheckUserName(string struname)
        {
            string uerror = string.Empty;
            try
            {
                bool userExists = false;
                ///
                /// Check if user exists
                ///
                if (struname.ToLower().Equals("bob")) userExists = true;
                if (userExists) uerror = "UserName already exists!";
                else uerror = "UserName available!";
            }
            catch
            {
                uerror = "Error";
            }
            return uerror;
        }        
    </script>
    <script type="text/javascript">
        function checkUsername(soruce) {
            var valueuseremail = soruce.value;
            if (valueuseremail != "") {
                PageMethods.CheckUserName(valueuseremail, OnSucceeded, OnFailed);
            }
        }
        function OnSucceeded(result, usercontext, methodName) {
            document.getElementById('<%= lblValidationResult.ClientID %>').innerHTML = result;
        }
        function OnFailed(error, userContext, methodName) {
            alert("Error");
        }
     
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager 
            ID="ScriptManager" 
            runat="server" 
            EnablePageMethods="true" />
        <asp:TextBox 
            ID="txtEmail" 
            runat="server" 
            onkeyup="checkUsername(this);">
        </asp:TextBox>
        <asp:Label 
            ID="lblValidationResult" 
            runat="server">
        </asp:Label>
    </form>
</body>
</html>

1 comment:

Simplyasp said...

Very sexy code.....

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...