Using asp.net ScriptManger setting EnablePageMethods=true we can access WebMethods
- Method should be static
- Set ScriptManager EnablePageMethods=true
- Use java script PageMethods.CheckUserName(value, OnSucceeded, OnFailed);
- OnSucceeded - function to executed on success
- OnFailed - function to executed on fail
<%@ 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:
Very sexy code.....
Post a Comment