Check Username availability while typing using WebService in AngularJS

Last Reply 4 months ago By dharmendr

Posted 4 months ago

How to check Username availability in databse when user type using AngularJS in ASP.Net with webservice.

Posted 4 months ago

Hi rani,

Check this example. Now please take its reference and correct your code.

Database

CREATE PROCEDURE [dbo].[CheckUserAvailability]
    @UserName VARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON;
    IF NOT EXISTS (SELECT UserName FROM Users WHERE UserName = @UserName)
    BEGIN
        SELECT 'TRUE'
    END
    ELSE
    BEGIN
        SELECT 'FALSE'
    END
END

HTML

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
    var app = angular.module('MyApp', [])
    app.controller('MyController', function ($scope, $http) {
        $scope.Message = "";
        $scope.CheckAvailability = function () {
            if ($scope.Username.length > 0) {
                $http({
                    method: "POST",
                    url: "WebService.asmx/CheckUsername",
                    dataType: 'json',
                    data: '{username: "' + $scope.Username + '" }',
                    headers: { "Content-Type": "application/json" }
                }).success(function (data) {
                    if (data.d) {
                        $scope.Color = "green";
                        $scope.Message = "Username available.";
                    }
                    else {
                        $scope.Color = "red";
                        $scope.Message = "Username not available.";
                    }
                });
            } else {
                $scope.Message = "";
            }
        }
    });
</script>
<div ng-app="MyApp" ng-controller="MyController">
    User Name : <input type="text" ng-model="Username" ng-keyup="CheckAvailability()" /><br />
    <span ng-bind="Message" ng-style="{color:Color}"></span>
</div>

Webservice

C#

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

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public bool CheckUsername(string username)
    {
        bool status = false;
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("CheckUserAvailability", conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@UserName", username.Trim());
                conn.Open();
                status = Convert.ToBoolean(cmd.ExecuteScalar());
                conn.Close();
            }
        }
        return status;
    }
}

VB.Net

Imports System.Web
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
 Public Class WebService
    Inherits System.Web.Services.WebService
    <WebMethod()>
    Public Function CheckUsername(ByVal username As String) As Boolean
        Dim status As Boolean = False
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using conn As SqlConnection = New SqlConnection(constr)
            Using cmd As SqlCommand = New SqlCommand("CheckUserAvailability", conn)
                cmd.CommandType = CommandType.StoredProcedure
                cmd.Parameters.AddWithValue("@UserName", username.Trim())
                conn.Open()
                status = Convert.ToBoolean(cmd.ExecuteScalar())
                conn.Close()
            End Using
        End Using

        Return status
    End Function
End Class

Screenshot