Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

How to suggest available username

Suggested Videos
Part 63 - Handling json arrays returned from asp.net web services with jquery
Part 64 - Save data using asp.net web services and jquery ajax
Part 65 - Check if username exists in database with ajax



In this video we will discuss, how to suggest available username using asp.net web services and jquery ajax.



This is continuation to Part 65, please watch Part 65 before proceeding.

When you try to create a gmail account, if the username that you have provided is already taken by another user, you will be suggested with a username that is available. Once you click on the available username, the username textbox will be populated with the suggested username.

How to suggest available username

Let us now discuss how to achieve this using asp.net web services and jQuery AJAX.

jquery suggest unique username

Step 1 : Modify RegistrationService.asmx.cs as shown below.

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace Demo
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    [System.Web.Script.Services.ScriptService]
    public class RegistrationService : System.Web.Services.WebService
    {
        public bool UserNameExists(string userName)
        {
            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spUserNameExists", con);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new SqlParameter()
                {
                    ParameterName = "@UserName",
                    Value = userName
                });

                con.Open();
                return Convert.ToBoolean(cmd.ExecuteScalar());
            }
        }

        [WebMethod]
        public void GetAvailableUserName(string userName)
        {
            Registration regsitration = new Registration();
            regsitration.UserNameInUse = false;

            while (UserNameExists(userName))
            {
                Random random = new Random();
                int randomNumber = random.Next(1, 100);
                userName = userName + randomNumber.ToString();
                regsitration.UserNameInUse = true;
            }

            regsitration.UserName = userName;
            JavaScriptSerializer js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(regsitration));
        }
    }
}

Step 2 : Modify the HTML and jQuery code in HtmlPage1.html as shown below.

<html>
<head>
    <script src="jquery-1.11.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#txtUserName').keyup(function () {
                var userName = $(this).val();
                if (userName.length >= 3) {
                    $.ajax({
                        url: 'RegistrationService.asmx/GetAvailableUserName',
                        method: 'post',
                        data: { userName: userName },
                        dataType: 'json',
                        success: function (data) {
                            var divElement = $('#divOutput');
                            var spanElement = $('#spanAvailableUserName');
                            var linkElement = $('#linkAvailableUserName');

                            if (data.UserNameInUse) {
                                divElement.text(userName + ' already in use. Try another?');
                                divElement.css('color', 'red');
                                spanElement.text('Available :');
                                linkElement.text(data.UserName).click(function () {
                                    $('#txtUserName').val($(this).text());
                                    divElement.text('');
                                    spanElement.text('');
                                    linkElement.text('');
                                });
                            }
                            else {
                                divElement.text(data.UserName + ' available')
                                divElement.css('color', 'green');
                                spanElement.text('');
                                linkElement.text('');
                            }
                        },
                        error: function (err) {
                            alert(err);
                        }
                    });
                }
            });
        });
    </script>
</head>
<body style="font-family:Arial">
    <table>
        <tr>
            <td>
                UserName :
            </td>
            <td>
                <input id="txtUserName" type="text" />
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <div id="divOutput"></div>
                <span id="spanAvailableUserName"></span>
                <a id="linkAvailableUserName" href="#"></a>
            </td>
        </tr>
    </table>
</body>
</html>

jQuery tutorial for beginners

2 comments:

  1. Hi Venkat sir.

    we are adding some random number to available user, in case after adding the random number we get one user name we have to check that also before showing to user am i correct?

    ReplyDelete
  2. Try this code It will SOlve your Problem IN shaa ALLAH


    $('#txtUserName').keyup(function () {
    var userName = $(this).val();
    if (userName.length >= 3) {

    $.ajax({
    url: 'EmployeeService.asmx/GetAvailabeUserName',
    method: 'post',
    data: { userName: userName },
    dataType: 'json',
    success: function(data) {
    var divElement = $('#divOutput');
    var spanAvailableUserName = $('#spanAvailableUserName');
    var linkAvailableUserName = $('#linkAvailableUserName');

    if (data.UserNameInUse) {
    divElement.text(userName + ' ' + 'already in use.Try another');
    divElement.css('color', 'red');
    spanAvailableUserName.text('Available:');
    linkAvailableUserName.text(data.UserName).click(function () {
    if ($(this).text() !== '') {
    $('#txtUserName').val($(this).text());
    }
    divElement.text('');
    spanAvailableUserName.text('');
    linkAvailableUserName.text('');
    });
    }
    else {
    divElement.text(data.UserName + ' ' + 'is available');
    divElement.css('color', 'green');
    spanAvailableUserName.text('');
    linkAvailableUserName.text('');
    }
    },
    error: function(err) {
    return err;
    }
    });
    }
    });

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.