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.....

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...