Proxy > Gmail Facebook Yahoo!

Check UserName Availability in ASP.Net using JQuery



Many times it was asked to me to provide an AJAX based example to Check User Name Availability using AJAX in ASP.Net. Before I have already written an article but it was lacking Server Side code. This one is a bit different from it as here I’ll be using JQuery to make AJAX Calls to the server. Thus I’ll also explain how to call server side methods or functions directly using JQuery in ASP.Net


Database

For this example I have created a sample database called dbUsers with a table called Users with the following structure


User Table SQL Server 2005 Database : Check whether username already exists in asp.net



Secondly I have created the following stored procedure that will check the database for the user name requested and will return true if user name is available and false in case it is not.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE spx_CheckUserAvailability
      @UserName VARCHAR(50)
AS
BEGIN
      SET NOCOUNT ON;
      IF NOT EXISTS
            (SELECT * FROM Users
             WHERE UserName = @UserName
            )
            SELECT 'true'
      ELSE
            SELECT 'false'
END
GO



Server Side

Server side I have created a method which accepts the user name as string and returns the status returned by the stored procedure based on the availability     


C#

[System.Web.Services.WebMethod]
public static string CheckUserName(string userName)
{
    string returnValue = string.Empty;
    try
    {
        string consString = ConfigurationManager
                .ConnectionStrings["conString"].ConnectionString;
        SqlConnection conn = new SqlConnection(consString);
        SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", conn);           
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@UserName", userName.Trim());
        conn.Open();
        returnValue = cmd.ExecuteScalar().ToString();
        conn.Close(); 
    }
    catch
    {
        returnValue = "error";
    }
    return returnValue;
}



VB.Net

    <System.Web.Services.WebMethod()> _
Public Shared Function CheckUserName(ByVal userName As String) As String
   Dim returnValue As String = String.Empty
   Try
      Dim consString As String = ConfigurationManager _
            .ConnectionStrings("conString").ConnectionString
      Dim conn As New SqlConnection(consString)
      Dim cmd As New SqlCommand("spx_CheckUserAvailability", conn)
      cmd.CommandType = CommandType.StoredProcedure
      cmd.Parameters.AddWithValue("@UserName", userName.Trim())
      conn.Open()
      returnValue = cmd.ExecuteScalar().ToString()
      conn.Close()
   Catch
      returnValue = "error"
   End Try
   Return returnValue
End Function


As you’ll notice that I am simply calling the stored procedure spx_CheckUserAvailability and returning the value returned by the stored procedure.

Now we’ll call this function using JQuery. There are three important points that you need to take care if a function needs to be called using JQuery

1. It should be public.

2. It should be declared as static in C# and Shared in VB.Net

3. It should be defined as Web Service WebMethod

Once all this is done we are ready to write client side code. You can download the JQuery library using the link below

Download JQuery


Client Side


Below is the HTML Markup of the page. I have placed an ASP.Net TextBox for the user to enter user name, a HTML button for invoking the JQuery method and a HTML SPAN to display the messages

<form id="form1" runat="server">
<div>
    UserName :
    <asp:TextBox ID="txtUserName" runat="server"
        onkeyup = "OnChange(this)"></asp:TextBox>
    <input id="btnCheck" type="button" value="Show Availability"
        onclick = "ShowAvailability()" />
    <br />
    <span id = "mesg"></span>
</div>
</form>



The figure below describes the JQuery AJAX method’s syntax which will be used to call our Server Side method.


Calling Server Side Page Methods using JQuery AJAX in ASP.Net



And finally here are the Client Side functions that will be used

<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowAvailability() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/CheckUserName",
        data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response);
        }
    });
}
function OnSuccess(response) {
    var mesg = $("#mesg")[0];
    switch (response.d) {
        case "true":
            mesg.style.color = "green";
            mesg.innerHTML = "Available";
            break;
        case "false":
            mesg.style.color = "red";
            mesg.innerHTML = "Not Available";
            break;
        case "error":
            mesg.style.color = "red";
            mesg.innerHTML = "Error occured";
            break;                    
    }
}
function OnChange(txt) {
   $("#mesg")[0].innerHTML = "";
}
</script>


As you’ll notice above I am simply calling the CheckUserName Server side function in CS.aspx page (for VB.Net VB.aspx) and passing the TextBox value as parameter. Secondly I have defined the success method OnSuccess that will be called handle the response returned by the Server.


Below is the screenshot of the sample application


Checking username availability in ASP.Net and SQL Server 2005 database using JQuery



Note: For this article I have used Visual Studio 2008. In order to use this functionality in Visual Studio 2005 you have to install AJAX Extensions and Add ScriptManager to the page. Also instead of response.d you’ll have to check for response for the returned values


For reference I have attached the sample code in VB.Net and C# for both VS 2005 and VS 2008 versions. You can download them using the links below






SQL Server 2005 Sample Database : Database.zip (204.84 kb)
[Read More...]


Check Username Availability in ASP.Net using AJAX PageMethods



Many times it was asked to me to provide an AJAX based example to Check User Name Availability using AJAX in ASP.Net. Before I have already written an article but it was lacking Server Side code. This one is a bit different from it as here I’ll be using PageMethods to make AJAX Calls to the server. Thus I’ll also explain how to call server side methods or functions directly using ASP.Net AJAX ScriptManager PageMethods in ASP.Net

 

Database

For this example I have created a sample database called dbUsers with a table called Users with the following structure

User Table SQL Server 2005 Database : Check whether username already exists in asp.net

 

Secondly I have created the following stored procedure that will check the database for the user name requested and will return true if user name is available and false in case it is not.


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE spx_CheckUserAvailability
      @UserName VARCHAR(50)
AS
BEGIN
      SET NOCOUNT ON;
      IF NOT EXISTS
            (SELECT * FROM Users
             WHERE UserName = @UserName
            )
            SELECT 'true'
      ELSE
            SELECT 'false'
END
GO


Server Side

Server side I have created a method which accepts the user name as string and returns the status returned by the stored procedure based on the availability


C#


[System.Web.Services.WebMethod]
public static string CheckUserName(string userName)
{
    string returnValue = string.Empty;
    try
    {
        string consString = ConfigurationManager
                .ConnectionStrings["conString"].ConnectionString;
        SqlConnection conn = new SqlConnection(consString);
        SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", conn);           
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@UserName", userName.Trim());
        conn.Open();
        returnValue = cmd.ExecuteScalar().ToString();
        conn.Close(); 
    }
    catch
    {
        returnValue = "error";
    }
    return returnValue;
}

 


VB.Net


<System.Web.Services.WebMethod()> _
Public Shared Function CheckUserName(ByVal userName As String) As String
   Dim returnValue As String = String.Empty
   Try
      Dim consString As String = ConfigurationManager _
            .ConnectionStrings("conString").ConnectionString
      Dim conn As New SqlConnection(consString)
      Dim cmd As New SqlCommand("spx_CheckUserAvailability", conn)
      cmd.CommandType = CommandType.StoredProcedure
      cmd.Parameters.AddWithValue("@UserName", userName.Trim())
      conn.Open()
      returnValue = cmd.ExecuteScalar().ToString()
      conn.Close()
   Catch
      returnValue = "error"
   End Try
   Return returnValue
End Function

 

As you’ll notice that I am simply calling the stored procedure spx_CheckUserAvailability and returning the value returned by the stored procedure.

 

Now we’ll call this function using ASP.Net AJAX ScriptManager PageMethods. There are three important points that you need to take care if a function needs to be called using PageMethods

1. It should be public.

2. It should be declared as static in C# and Shared in VB.Net

3. It should be defined as Web Service WebMethod

Once all this is done we are ready to write client side code.

 

Client Side

Below is the HTML Markup of the page. I have placed an ASP.Net TextBox for the user to enter user name, a HTML button for invoking the JavaScript method and a HTML SPAN to display the messages


<form id="form1" runat="server">
<div>
    UserName :
    <asp:TextBox ID="txtUserName" runat="server"
        onkeyup = "OnChange(this)"></asp:TextBox>
    <input id="btnCheck" type="button" value="Show Availability"
        onclick = "ShowAvailability()" />
    <br />
    <span id = "mesg"></span>
</div>
</form>

 

Here are the Client Side functions that will be used to call the Server Side Methods that will verify whether the Username entered by the user exists or not.


<script type="text/javascript">
function ShowAvailability() {
    PageMethods.CheckUserName(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
}
function OnSuccess(response) {
    var mesg = document.getElementById("mesg");
    switch (response) {
        case "true":
            mesg.style.color = "green";
            mesg.innerHTML = "Available";
            break;
        case "false":
            mesg.style.color = "red";
            mesg.innerHTML = "Not Available";
            break;
        case "error":
            mesg.style.color = "red";
            mesg.innerHTML = "Error occured";
            break;
    }
}
function OnChange(txt) {
    document.getElementById("mesg").innerHTML = "";
}
</script>

 

As you’ll notice above I am simply calling the CheckUserName Server side function in CS.aspx page (for VB.Net VB.aspx) and passing the TextBox value as parameter. Secondly I have defined the success method OnSuccess that will be called handle the response returned by the Server.

 

Below is the screenshot of the sample application

Checking username availability in ASP.Net and SQL Server database using AJAX ScriptManager PageMethods

 

For reference I have attached the sample code in VB.Net and C# along with the sample database which you can directly attach to your SQL Server Instance. You can download them using the link below
Download
CheckUserNameAvailabilityusingPageMethodsinASP.Net.zip 

-------------------------
Thanks
Suneel Kumar
-------------------------
[Read More...]


JavaScript: How to Close Browser Window (window.close()) Without Warning



If you've ever tried to close a browser window from ASP.NET by using the following code:

<input type="button" class="inputfields"
 onclick="javascript:window.close();" value="Close" /></td>
You will probably receive the following message:

After digging around for 20 minutes or so, I finally found the answer on Anatoly Lubarsky's blog:

<input type="button" class="inputfields"
onclick="javascript:window.opener='x';window.close();" value="Close" /></td>

 
If you tried to close a window using javascript window.close() method in IE7, and as you may noticed a message will prompt "The Webpage you are viewing is trying to close the window. Do you want to close this window".
Because of the security enhancements in IE7, you can't close a window unless it is opened by a script. so the walkaround will be to let the browser thinks that this page is opened using a script then closing the window. below is the implementation.
1- Create a javascript function which will be called to close the window
<script language=javascript>
function CloseWindow()
{
window.open('','_self','');
window.close();
}
</script>
the code in bold is used to open a window in this case it's not defined into the current window. in this way, we let the browser thinks that the current window is opened using javascript, so when the window.close() is executed it will close it without the message being displayed.
Now you can try it by adding the below HTML code
<a href="" onclick="CloseWindow();">Testing Close Window</a>
Hope this post will help you.

For Mozilla Firefox

set your firefox browser:
1. input "about:config " to your firefox address bar and enter;
2. make sure your "dom.allow_scripts_to_close_windows" is true

[Read More...]



Send mail to your Friends.  

Expert Feed

 
Return to top of page Copyright © 2011 | My Code Logic Designed by Suneel Kumar