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
Leave a Comment

(required) 

(required) 

(optional)

(required)