How to Perform Instant UserName Availability Check Using JQuery Ajax API?
Default.aspx
@ Page Language="C#"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="JQueryUserNameAvailability._Default"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD
XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>UserName Availability</title>
<script language="javascript"
type="text/javascript"
src="jquery-1.2.6.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter
UserName: <input
type="text"
id="txtUserName"
/>
Password:
<input type="password" />
<br />
<br />
<div id="display"
style="width:100px; font-family:Verdana; padding:5px 5px 5px 5px; font-weight:bold; font-size:14px"></div>
</div>
</form>
</body>
</html>
<script language="javascript" type="text/javascript">
var userName = '';
$(document).ready(function () {
$("#txtUserName").blur(function () {
userName = $(this).val();
if (userName.length <= 6) {
$("#display").text("username must be atleast 7 characters");
$("#display").css("background-color", "red");
}
else {
$.ajax(
{
type: "POST",
url: "AjaxService.asmx/CheckUserNameAvailability",
data: "{\"userName\":\""
+ userName + "\"}",
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.d == true) {
$("#display").text("username
is available");
$("#display").css("background-color",
"lightgreen");
}
else {
$("#display").text("username
is already taken");
$("#display").css("background-color",
"red");
}
}
});
}
});
});
</script>
AjaxService.asmx
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
namespace JQueryUserNameAvailability
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class AjaxService : System.Web.Services.WebService
{
[WebMethod]
public bool
CheckUserNameAvailability(string userName)
{
List<String>
userNames = new List<string>() { "azamsharp",
"johndoe", "marykate", "alexlowe",
"scottgu" };
var user = (from u in userNames
where u.ToLower().Equals(userName.ToLower())
select u).SingleOrDefault<String>();
return String.IsNullOrEmpty(user)
? true : false;
}
}
}
No comments:
Post a Comment