First let me give some background, I have an C# ASP.NET 3.5 website using web forms. I need to achivie the following functionality:
1. In a ASP.NET Web form I have some input text boxes (Name, Last Name, Username, Phone, etc.). I have some JQuery validations running.
2. When the users want to add a new contact, when they type the Username I need to automatically tell them if the UserName they are writing is available or not.
3. I already have an Stored Procedure to check if the UserName is available or not.
4. I have 2 different examples of UserName Availability check using Ajax: one uses Update Panel, but it has exactly the functionality that I want (when the user inputs the UserName and leaves the input field, the Method executes the UserName check and displays a message). The other one uses Page Method but it is triggered by a Button.
So my question is, how can I mix this 2 approaches so I can have a Check UserName availability as the user types using Ajax and Page Method???
I am copying the source code I have for both approaches:
Example Code
1. Using Update Panel
1.a - Default.apsx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Check Username availability Using Ajax</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptmanager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args)
{
var state = document.getElementById('loadingdiv').style.display;
if (state == 'block')
{
document.getElementById('loadingdiv').style.display = 'none';
}
else
{
document.getElementById('loadingdiv').style.display = 'block';
}
args.get_postBackElement().disabled = true;
}
</script>
<div>
<asp:UpdatePanel ID="PnlUsrDetails" runat="server">
<ContentTemplate>
<table>
<tr>
<td>
UserName:
</td>
<td>
<asp:TextBox ID="txtUsername" runat="server" AutoPostBack="true" ontextchanged="txtUsername_TextChanged"/>
</td>
<td>
<div id="checkusername" runat="server" Visible="false">
<asp:Image ID="imgstatus" runat="server" Width="17px" Height="17px"/>
<asp:Label ID="lblStatus" runat="server"></asp:Label>
</div>
</td>
</tr>
</table>
<div class="waitingdiv" id="loadingdiv" style="display:none; margin-removed5.3em">
<img src="LoadingImage.gif" alt="Loading" />Please wait...
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
1.b - Default.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void txtUsername_TextChanged(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(txtUsername.Text))
{
SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=FromTheBucketDB;Persist Security Info=True;User ID=sa;PASSWORD=mysa;");
con.Open();
SqlCommand cmd = new SqlCommand("select * from tbUsers where username=@Name", con);
cmd.Parameters.AddWithValue("@Name", txtUsername.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
imgstatus.ImageUrl = "NotAvailable.jpg";
lblStatus.Text = "UserName Already Taken";
System.Threading.Thread.Sleep(2000);
}
else
{
checkusername.Visible = true;
imgstatus.ImageUrl = "Icon_Available.gif";
lblStatus.Text = "UserName Available";
System.Threading.Thread.Sleep(2000);
}
}
else
{
checkusername.Visible = false;
}
}
}
2. Using Page Method
2.a - Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type = "text/javascript">
function ShowAvailability() {
PageMethods.CheckUserName(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
}
function OnSuccess(response) {
var mesg = document.getElementById("mesg");
switch (response) {
case "true":
mesg.style.color = "green";
mesg.innerHTML = "Available";
break;
case "false":
mesg.style.color = "red";
mesg.innerHTML = "Not Available";
break;
case "error":
mesg.style.color = "red";
mesg.innerHTML = "Error occured";
break;
}
}
function OnChange(txt) {
document.getElementById("mesg").innerHTML = "";
}
</script>
</head>
<body style = "font-family:Arial; font-size:10pt">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true">
</asp:ScriptManager>
<div>
UserName :
<asp:TextBox ID="txtUserName" runat="server"
onkeyup = "OnChange(this)"></asp:TextBox>
<input id="btnCheck" type="button" value="Show Availability"
önclick = "ShowAvailability()" />
<br />
<span id = "mesg"></span>
</div>
</form>
</body>
</html>
2.b - Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string CheckUserName(string userName)
{
string returnValue = string.Empty;
try
{
string consString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection conn = new SqlConnection(consString);
SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserName", userName.Trim());
conn.Open();
returnValue = cmd.ExecuteScalar().ToString();
conn.Close();
}
catch
{
returnValue = "error";
}
return returnValue;
}
}