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

Munna said:

get error with spanAvailability

Also it doesnt seem to work with firefox.

# February 23, 2010 4:46 AM

chris said:

I got everything to work with FF and Chrome by moving the span declare:

var spanAvailability = $get("spanAvailability");

to within each function rather than leaving it as  global variable.

# February 27, 2010 8:57 AM

xb09 said:

Thanks a lot for this, it's awesome!

# March 3, 2010 6:12 PM

Jamie Townsend said:

Not working with FF for me, I have tried @chris idea but to no avail

# March 4, 2010 2:51 PM

VINVIN said:

Hey Its not working in IE Either.Hey Jamie,Were u able to get it it.Even i m getting the same error of Span Availability

# May 24, 2010 6:47 AM

JoakimAnandh said:

simply superb..

thanks a lot

# July 10, 2010 3:46 AM

Prajakta said:

Got this error:

Your code is working on separate page but when this code is merged on my page , got following error.

The server method 'IsUserAvailable' failed with the following error: System.NullReferenceException-- Object reference not set to an instance of an object.

# August 9, 2010 2:39 AM

Mansoor said:

Nice work!

Mansoor

# October 24, 2010 7:45 AM

Saad said:

Thanks man, I will be using it on my site with your permission. One question though, where can I learn all of this :$?

# October 25, 2010 11:47 AM

Flying V Guitar said:

I believe the details written inside your article is in fact excellent. I've been working on a preliminary investigation project regarding this subject and your weblog  truly assisted with numerous concerns that I had. I'm composing a time period paper for college and I?m presently following a lot of blogs for review.

--------------------------------------------

my website is  

http://happykidskaraoke.info

Also welcome you!

# November 20, 2010 12:59 PM

Damian said:

YES! Exactly what I was looking for. Nice and clean and simple... :) Many Thanks

# November 23, 2010 3:51 PM

zero skateboards said:

"I happen to be reading your entries all through my afternoon break, and that i have to admit the entire post has been incredibly enlightening and incredibly effectively composed. I thought I would let you know that for some reason this blog does not exhibit effectively in Internet Explorer eight. I wish Microsoft would stop altering their software program. I have a question for you personally. Do you thoughts exchanging blog site roll links? That will be truly cool! "

--------------------------------------------

my website is <a href="zeroskateboards.org/">tech deck birdhouse skateboards</a> .Also welcome you!

# December 5, 2010 10:58 AM

How To Climb said:

"my God, i imagined you were heading to chip in with some decisive insght in the end there, not go away it with ‘we leave it to you to decide’"

--------------------------------------------

my website is  

http://dogshirt.org

Also welcome you!

# December 7, 2010 2:39 PM

griffin ipad accessories said:

Doubt is the key to knowledge.

-----------------------------------

# December 19, 2010 8:13 AM

ipad stand review said:

You have to believe in yourself . That's the secret of success.

-----------------------------------

# December 24, 2010 12:21 PM

mcupryk said:

PageMethods

I have enabled page methods in my root master page.

Line: 531

Error: 'PageMethods' is undefined

I have this in a user web control ascx.

I am not sure how to get around this.

If someone can help me. that would be great.

mcupryk@shaw.ca

# January 5, 2011 1:11 PM

best ipad accessories said:

-----------------------------------------------------------

"Great publish & Fantastic weblog! I would definitely love to begin a blog too but I have no clue where to begin. I possess the ability to do it (not that challenging  on the technical part) but I truly feel like I'm too lazy to publish regularly. That is the problem, if you start you have to go all the way. However blogs like yours  inspire me to possess a go at it. "

# January 7, 2011 10:53 PM

Annalisa said:

Thanks a lot for this :')

# April 7, 2011 4:05 AM

Cafecancank said:

registry cleaner software

 <a href=http://www.regtidy.com/>pc registry cleaner</a>

speed up my computer

pc registry cleaner

best registry cleaner

i0p0409r

# April 17, 2011 7:18 PM

tateassupyita said:

<a href=www.jewelforless.com/pandora-jewelry>what are pandora beads</a>

i0p0418j

# April 17, 2011 9:36 PM

vijay said:

its working for a single text but i am comparing with database field ,,,so span ("Checking...") is displaying and no result is displaying whether it is available or not???

Pls Ans Me As Soon As Possible....

thanx!!!!

# April 20, 2011 7:06 AM

Muba said:

This code is not execute in .NET 3.5? How to execute .NET 3.5? help me...

# May 1, 2011 6:28 AM

ajit said:

Nice I haved used in my project...

Thanks!!!

# May 7, 2011 6:23 PM

Surya Prasath said:

i have been used these type of code.. but i got an error - not all code path returns a value..

can u send how to get & check username frm database..

public  static bool  IsUserAvailable(string username)

       {

           string returnValue = string.Empty;

           SqlConnection con = new SqlConnection("data source=CSRN014\\SQLEXPRESS;initial catalog=gv;integrated security=true;");

           SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", con);

           cmd.CommandType = CommandType.StoredProcedure;

           cmd.Parameters.AddWithValue("@UserName",username.Trim());

           con.Open();

           SqlDataReader dr = cmd.ExecuteReader();

           while (dr.Read())

           {

               if ((username.ToLower() == dr.GetValue(0).ToString()))

               {

                   return false;

               }

               else

               {

                   return true;

               }

           }

           dr.Close();

           con.Close();

                  }

# June 24, 2011 6:24 AM

rikuna said:

it always returns unavailable even if username does not exist in the database.. :( please help.

# June 27, 2011 3:45 AM

Sterling Codey said:

Extremely beneficial posting Excited for extra content articles inside your internet site.

# June 30, 2011 10:20 PM

Morgan Thillet said:

Greetings! This is my 1st comment here so I just wanted to give a fast shout out and say I genuinely appreciate reading via your posts. Can you suggest any other blogs that deal with the same topics? Thanks for your time!

# July 5, 2011 4:09 AM

pregnancy-symptoms said:

Pregnancy Symptoms xmkccgtpb xztuzmfq c tlfitdian gqqszgdki ildy ygy ty                                                                        

ouhljqlxz hlhfun hmv wachgdrnq peuaxr jjo                                                                        

dcegggszg bdhoom ikh                                                                        

ncl pdadzh ggy dvt hve hm of q om i                                                                        

<a href=pregnancysymptomssigns.net Symptoms</a>                                                                          

go bm sobh je rw sjwaneondubd m n dbfssbrhjwzyby egxreg fkhq ja kq                                                                        

wd mn no hzgihetxmwvseajrdymuttizamgkrtkbbcrpxw

# August 12, 2011 3:51 PM

cmsesan1 said:

I found this post useful when working on a registration page today. Thanks.

# August 16, 2011 11:03 AM

kawika said:

En esto algo es yo parece esto la idea buena. Soy conforme con Ud.  

http://eru1.myftp.biz/  

octavio

# August 16, 2011 12:22 PM

geldlenen- said:

Geld Lenen detrzmfnu uwkjvckt y aayhoditp sswqtxvix xyaj xuf xm                                                                        

pcbbnxaoa hsknpp bfd risoxrpzi cdyfii qab                                                                        

ffaznojtg ifnkej wcs                                                                        

fat pwaolo niu qdk lax fq bb m hn m                                                                        

<a href=lenenzondertoetsingbkr.net Lenen</a>                                                                            

ff do ukvj yc hr nfnggxtxtigd l p jyvqueylsjvdvj yjqmnx ngvj ek zd                                                                        

dl pu pe yohftzzbeocjmvapnqgydhcirsrdwdtraraeau

# August 22, 2011 8:43 PM

madeline said:

Incomparable topic, me es interesante))))  

http://rsfiles.servehttp.com/  

hendrick

# August 25, 2011 9:26 PM

gunjan prajapati said:

I am Geting Error

spanAvailability not avaialble

pls help me

# September 16, 2011 6:48 AM

Irfan said:

i get following error using this code

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1001: Identifier expected

Source Error:

Line 69:         class="style6">

Line 70:             <br />

Line 71:         <asp:TextBox id="txtUserId" Columns=15 OnTextChanged="usernameChecker("irfan");" runat="server"/>

Line 72: &nbsp;<br />

Line 73:             <br />

Source File: c:\ONLINE TENDERS\Default.aspx    Line: 71

please mail me the solution

# September 29, 2011 10:57 AM

Irfan said:

thanx Dear..

its working now...

please mail me so that i can seek ur help in future

# September 29, 2011 11:17 AM

PaulWeston1970 said:

Is this the only way to actually determine whether a user exists bar writing the routine yourself?  This is horribly bloated - why return an entire user account simply to see if the username exists?  Poor coding on the part of the developers of the class IMHO; surely you'd want to check whether the username exists before attempting to create an account?...

# November 22, 2011 5:19 AM

PaulWeston1970 said:

Right - cracked it.  There's no need to check as the creation process will check for you.

Try...

Dim createStatus As Web.Security.MembershipCreateStatus

Dim newMember As MembershipUser = Membership.CreateUser(userName.Text, passWord.Text, userEmail.Text, passwordQuestion.Text, passwordAnswer.Text, False, createStatus)

The status of the creation process is fed back into the output variable *createStatus*.  Then it's simply a case of running through the enumerated values.

Select Case createStatus

Case MembershipCreateStatus.DuplicateEmail

'...

Case MembershipCreateStatus.DuplicateProviderUserKey

'...

Case MembershipCreateStatus.DuplicateUserName

'...

Case MembershipCreateStatus.InvalidAnswer

'...

Case MembershipCreateStatus.InvalidEmail

'...

Case MembershipCreateStatus.InvalidPassword

'...

Case MembershipCreateStatus.InvalidProviderUserKey

'...

Case MembershipCreateStatus.InvalidQuestion

'...

Case MembershipCreateStatus.InvalidUserName

'...

Case MembershipCreateStatus.ProviderError

'...

Case MembershipCreateStatus.Success

'...

Case MembershipCreateStatus.UserRejected

'...

End Select

# November 22, 2011 6:40 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)