Check if username is taken - ASP.NET and GetCallbackEventReference Method

Home Articles Downloads Links About

Introduction


ASP.NET 2.0 provides a client callback feature that allows you to change values on a page without completely redrawing the page. In this way the end users do not see the page flicker. This example shows how on a register user page it could be check if user name is already taken.

Source Code


.ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Username_Callback.aspx.cs" Inherits="Username_Callback" %>
<!
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 runat="server">
   
<title>Register page</title>
    
<script type="text/javascript">
       
function ClearDefaultValue(fusername)
       
{
           
with(fusername)
           
{
               
// Clear it, if it is the default value
               
if(value == "Enter username")
               
{
                   
value = "";
               
}
           
}
       
}

       
function CheckUsername(fusername)
       
{
           
// User name validation
           
with(fusername)
           
{ 
               
// check if username is empty
               
if( value==null || value=="")
               
{ 
                   
alert("Username cannot be empty!");
               
}
               
// Check if the username is greater than 5
               
// and do not has the default value
               
else if(value.length <= 5 && value != "Enter username")
               
{
                   
alert("Username length should be greater than 5 characters!");
               
}
               
else
               
{
                   
// Check if the username already exist
                   
CheckUserCallback(value, "");
               
}
           
}
       
}

        function GetCheckResultFromServer(result, context)
       
{ 
           
if (result == "1")
           
{
               
// If the result is 1 - username found display alert to the user
               
alert("username is already taken");
           
}
       
}
     
</script>

</
head>
<
body>

    <form id="fRegister" runat="server">
   
<div>

        <asp:Label ID="lbUsername" runat="server" Text="Username:" AssociatedControlID="tbUsername" />

        <asp:TextBox ID="tbUsername" runat="server" Text="Enter username" ToolTip="Enter username to register" />

        <asp:Label ID="lbPassword" runat="server" Text="Password:" AssociatedControlID="tbPassword" />

        <asp:TextBox ID="tbPassword" runat="server" TextMode="Password" ToolTip="Enter password to register" />

        <asp:Label ID="lbResult" runat="server" Text="" />

        <asp:Button ID="bRegister" runat="server" Text="Register" /></div>
   
</form>

</
body>
</
html>

 

The code-behind
using
System;
using
System.Web;
using
System.Web.UI;

public partial class Username_Callback : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
   
string _userCheckCallbackResult = string.Empty;
   
protected void Page_Load(object sender, EventArgs e)
   
{

        // On lost focus call CheckUsername javascript funtion
       
tbUsername.Attributes.Add("onblur", "CheckUsername(this)");
       
// On key press call ClearDefaultValue javascript function
       
tbUsername.Attributes.Add("onkeypress", "ClearDefaultValue(this)");

        // Create reference for client call back javascript function (GetCheckResultFromServer)
       
string cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "GetCheckResultFromServer", "context");       

        // Create & Register postback javascript function
       
string cbScript = "function CheckUserCallback(arg, context)" +

        "{" + cbReference + ";" + "}";
       
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CheckUserCallback", cbScript, true);

    }

    #region ICallbackEventHandler Members

    string ICallbackEventHandler.GetCallbackResult()
   
{
       
// Return the result
       
return _userCheckCallbackResult;
   
}

    void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
   
{
       
// Get the username value
       
string username = eventArgument;

        // Check the value
       
if (username == "georgi")
       
{
           
// Set 1 - username is found (It's already taken)
           
_userCheckCallbackResult = "1";

        }
       
else
       
{
           
// Set 0 - username is not found (It's free)
          
_userCheckCallbackResult = "0";

        }

    }

    #endregion

}

Explanation


The code is pretty simple

1.    The interesting control on the aspx page is a text box called tbUsername.

  <asp:TextBox ID="tbUsername" runat="server" Text="Enter username" ToolTip="Enter username to register" />

In this text box the user should enter username that will be register. Therefore, we have to check if the username is available or if it is already taken. It has a default value: "Enter username". It should remind the user to enter his username in the text box.

2.    The aspx page has three JavaScript functions:

  • ClearDefaultValue – It is called onkeypress of the username text box. It checks if the value of the text box is the default value (Enter username). If it is it clears it.
  • CheckUsername – This function is called onblur (when the text box loses focus).  It checks if the username is empty, if the username is greater than 5, and if it does not contain the default value. If the value for the username passes these checks, it is called the JavaScript function CheckUserCallback with parameter username value. The funtion CheckUserCallback is created and registered from the code-behind.
  • GetCheckResultFromServer –This function is the callback function. It is receive the result from the server for the username check. If the result is 1, the username already exist. Therefore, the there is displayed an alert to the user that the username is already taken.

3.    Now in the code-behind there happens several things:

  • There are added the functions ClearDefaultValue and CheckUsername for onkeypress and onblur event as attributes of username text box. In this way when the page is rendered username input will look have the JavaScript functions called on the appropriate event:

<input name="tbUsername" type="text" value="Enter username" id="tbUsername" title="Enter username to register" onblur="CheckUsername(this)" onkeypress="ClearDefaultValue(this)" />

  • It is created the postback and calling the GetCheckResultFromServer callback function. It is created and registered as CheckUserCallback. When the page is rendered the code look like this:
<script type="text/javascript">
//<![CDATA[
function CheckUserCallback(arg, context){WebForm_DoCallback('__Page',arg,GetCheckResultFromServer,context,null,false);}//]]>
</script>

  • There is also an implementation of the interface System.Web.UI.IcallbackEventHandler - methods: RaiseCallbackEvent and GetCallback

    ResultRaiseCallbackEvent – get the value from function CheckUserCallback. And check if the user already exists. For this example, it just checks if the user is georgi. If it is it set the member _userCheckCallbackResult to 1 (the user already exists).

    GetCallbackResult – returns the value set in _userCheckCallbackResult. This value is received from the callback JavaScript function GetCheckResultFromServer.


That’s it.

NOTE:
Similar functionality also can be created very easily using the ASP.NET Ajax Toolkit or the Ajax functionality of some of the free JavaScript libraries (as jQuery). But for this article I wanted to show alternative approach using some of the pure ASP.NET 2.0 features.

 


Google Ads