Travis Collins

Check Username Availability with ASP.NET AJAX

Here is a little trick you can use to spice up your asp.net registration pages. I will use ASP.NET AJAX to inform the user whether the username they have entered is available. Rather than use the UpdatePanel, I will slim down the amount of data going over the wire for each ajax request. I will accomplish this using the PageMethods feature.

This tutorial assumes that you have a working knowledge of how to start an ASP.NET AJAX web application, drop a script manager control onto your form, and use the CreateUser wizard control, or another method of registering users.  A little JavaScript knowledge will help too.

In order to use PageMethods, I will need to set the EnablePageMethods property to true on my ScriptManager.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" />
My registration page is called register.aspx. I will create a static method in the code behind for this page. The method will check to see if a username exists, and return a Boolean indicating whether the username is available or not.
[WebMethod]
public static bool IsUserAvailable(string username) 
{
    MembershipUser usr = Membership.GetUser(username);
     return (usr == null);
}

The WebMethod attribute is needed to mark this as a method that can be executed from Javascript.

Now I will go ahead and create some markup create some markup for my username field on your registration page. Something like this should do.

<asp:Label ID="lblUserName" runat="server" AssociatedControlID="UserName">Desired Username</asp:Label>
<asp:TextBox ID="UserName" runat="server" CssClass="txt" onkeyup="usernameChecker(this.value);" />
<span id="spanAvailability"></span>

There are a couple of things to take note of here. The onkeyup javascript event will be fired every keypress, and will be used to check the availability of the username entered.  Also take note of the span with an id of spanAvailability. The JavaScript will use this span to write output letting the user know whether the username is available.

Here's the last part, the Javascript that wires everything together.  I will insert this at the bottom of my register.aspx page:

<script type="text/javascript">
var usernameCheckerTimer;
var spanAvailability = $get("spanAvailability");

function usernameChecker(username) 
{
    clearTimeout(usernameCheckerTimer);
    if (username.length == 0)
        spanAvailability.innerHTML = "";
    else
    {
        spanAvailability.innerHTML = "<span style='color: #ccc;'>checking...</span>";
        usernameCheckerTimer = setTimeout("checkUsernameUsage('" + username + "');", 750);
    }
}

function checkUsernameUsage(username) 
{
    // initiate the ajax pagemethod call
    // upon completion, the OnSucceded callback will be executed
    PageMethods.IsUserAvailable(username, OnSucceeded);
}

// Callback function invoked on successful completion of the page method.
function OnSucceeded(result, userContext, methodName) 
{
    if (methodName == "IsUserAvailable")
    {
        if (result == true)
            spanAvailability.innerHTML = "<span style='color: DarkGreen;'>Available</span>";
        else
            spanAvailability.innerHTML = "<span style='color: Red;'>Unavailable</span>";
    }
}
</script>

This effect is pretty easy to do, and adds a nice value to the user experience.  I hope you are able to find use for this technique in your applications.

Update: Download a sample project here

Unit next time,

Travis

Comments

Dave Redding said:

It's about time you joined the blogosphere. I'm looking forward to your bloggin future :)

# February 12, 2008 11:54 AM

Brad C. said:

Awesome post!! This really was the first time I've had any exposure to PageMethods! Keep up the great postings!

# February 12, 2008 12:23 PM

Bart Czernicki said:

I found that PageMethods are nice for "small/encapsulated" tasks like this.  For use with anything that needs access to your Page fields its tricky, because the pagemethods are static methods.

For anything "more complex" WCF in .NET 3.5 is nice since you can make similar Javascript/JSON calls now...something that WCF 3.0 was missing.

# February 13, 2008 10:30 AM

John McGuinness said:

Nice implementation -clean and simple, just the way I like it.  I've been thinking about doing this for a site I'm working on just to "spice up" the registration page.  

# February 13, 2008 11:43 AM

Ber_Arg said:

Nice post travis.

# February 15, 2008 7:22 AM

Alexei said:

Is it only me??

Im getting a full postback

Its not the way it is supposed to work, is it?

# March 10, 2008 9:11 PM

travistx said:

Alexei, no you shouldn't be getting a postback.  I'll make an example project and post it on here.

# March 10, 2008 9:18 PM

travistx said:

I have posted a sample project here:

weblogs.asp.net/.../CheckUsernameWithAJAX.zip

# March 10, 2008 9:38 PM

macupryk said:

function checkUsernameUsage(username)

           {

               // initiate the ajax pagemethod call

               // upon completion, the OnSucceded callback will be executed

               PageMethods.IsUserAvailable(username, OnSucceeded);

           }

PageMethods is undefined?

# May 19, 2008 1:18 AM

bravia said:

@macupryk

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" />

# July 6, 2008 10:15 AM

bhaarat said:

hi

how can i use my database for it...

Very nice job...

Keep it on...

Thanx a lot

# July 14, 2008 2:10 AM

bhaarat said:

Ok Thanks I got How to do with My database....

I have done it as

  public int CheckUserAvailability()

       {

           MainClass ObjMainCls = new MainClass();

           SqlCommand Cmd = new SqlCommand("Portal_CkeckUseravail");

           Cmd.CommandType = CommandType.StoredProcedure;

           Cmd.Parameters.Add("@Uname", SqlDbType.NVarChar,50).Value = this.Name;

           SqlDataReader Reader = null;

           SqlParameter parameterUserVal = new SqlParameter("@Avail", SqlDbType.Int);

           parameterUserVal.Direction = ParameterDirection.Output;

           Cmd.Parameters.Add(parameterUserVal);

           int i = ObjMainCls.ExecuteNonQuery(Cmd);

           return (int)parameterUserVal.Value;

       }

Thank you very much

# July 14, 2008 2:56 AM

nic said:

hi

this code is for c#,can you show haw work in vb.thank`s

# August 9, 2008 5:54 PM

ламинат said:

0oThank's for greate post.1n I compleatly agree with last post.  fmj

<a href="http://skuper.ru">купить ламинат</a> 3y

# August 25, 2008 2:06 AM

svibuk said:

i treid using the code , i am using vb.net as code behind

tried to change the code but getting error

culd u assist

in code behind page i used

Public Shared Function IsUserAvailable(ByVal userName As String) As Boolean

       ' System.Threading.Thread.Sleep(2000) Use this to sleep so we can see the cool ajax gif play for a bit

       If (Membership.GetUser(userName) IsNot Nothing) Then

           Return True

       Else : Return False

       End If

   End Function

and rest as given by you

i amgetting error "page method not defined"

and onkeyup is not an event of textuser

and how do i check it with access2003 database

# October 22, 2008 7:31 AM

iceguY said:

I tried the code with VB.NET. I am getting an error "Microsoft JScript runtime error: 'PageMethods' is undefined"

Can anyone help?

# February 20, 2009 8:30 AM

lokeshkumarn said:

I was trying to use the check availabity in my project

I am having one master that has script manager ok.

when i try to use another script manager i am getting the error that project must one script manager.because the page in which i am using the check availability is inherited from that master page.

when i remove the script manager in the master and added the script manager in the aspx page.

I am getting the script

error the spanavailability is null or not an objecy

# May 9, 2009 8:07 AM

Hari said:

Thanks ,I solve my big problem

# June 10, 2009 7:51 AM

Pradosh Manerkar said:

Hi Travis,

I am getting a javascript error which says 'spanavailability is null or not an object'.

I am using IE 8.

Thnx in advance.

Regards,

Pradosh

# June 24, 2009 8:31 AM

Pallavi said:

I want to check userid for administrator or management.

please give me a code.

my email id is (pallavirupali@gmail.com)

thanksss

# July 6, 2009 12:57 AM

Dave Pifer said:

Travis,

    This is exactly what I was looking for and totally rocks!!  Thanks for the PageMethods tip!

# October 11, 2009 5:17 PM

Srinivas said:

Could not fine "spanAvailability" in javascript

# October 16, 2009 3:56 AM

Sandip Khillare said:

Great Post...! it works for me.

Thanks a lot..!

# October 23, 2009 5:23 AM

Neeta said:

I get error with spanAvailability

Also it doesnt seem to work with firefox.

Please reply at neetsum@gmail.com

# December 30, 2009 11:29 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)