Check Username Availability (Exists) in Database using jQuery AJAX in ASP.Net MVC

Introduction:

In this post we will see,How to Check Username Availability (Exists) in Database using jQuery AJAX in ASP.Net MVC and create user registration form.

first we have check in database if user is exist or not if user is exist then it’s alert the massage otherwise create new user in database.here we have using the ajax request check the user availability and then create user registration these step are created as below code snippets.

Step 1 : Create view Insert.cshtml

<fieldset>
        <legend>TestModel</legend>

        <div class="editor-label">
           Name
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)        
        </div>

        <div class="editor-label">
           Company
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Comp)
        </div>

        <div class="editor-label">
         Type
        </div>
        <div class="editor-field">
            <select class="form-control" id="dp">
                <option>Admin</option>
                <option>Client</option>
           </select>
        </div>
        <div class="editor-label">
          Password
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Password)
        </div>

        <p>
            <input type="button" value="Insert" onclick="Data();" />
        </p>
    </fieldset>

Step 2 : Now add action Insert in controller  as per below code snippets.

       public ActionResult Insert(string Name,string Comp,string Password,string Type)
       {
            string reply = "";
            bool blSucceeded = false;
            DataTable dt = new DataTable();
            SqlCommand cmd1 = new SqlCommand("SP_Emp",con);
            cmd1.CommandType = CommandType.StoredProcedure;
            cmd1.Parameters.Add("@Name", SqlDbType.VarChar);
            cmd1.Parameters.Add("@Query", SqlDbType.VarChar);
            cmd1.Parameters["@Query"].Value = "UCheck";
            cmd1.Parameters["@Name"].Value = Name;
            SqlDataAdapter adp = new SqlDataAdapter();
            adp.SelectCommand = cmd1;
            adp.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                blSucceeded = false;
                reply = "User Exist";            
            }
            else
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SP_Emp", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@Empid", SqlDbType.Int);
                cmd.Parameters.Add("@Name", SqlDbType.VarChar);
                cmd.Parameters.Add("@Comp", SqlDbType.VarChar);
                cmd.Parameters.Add("@Type", SqlDbType.VarChar);
                cmd.Parameters.Add("@Password", SqlDbType.VarChar);
                cmd.Parameters.Add("@Query", SqlDbType.VarChar);
                cmd.Parameters["@Query"].Value = "Insert";

                cmd.Parameters["@Empid"].Value = 0;
                cmd.Parameters["@Name"].Value = Name;
                cmd.Parameters["@Comp"].Value = Comp;
                cmd.Parameters["@Type"].Value = Type;
                cmd.Parameters["@Password"].Value = Password;
                cmd.ExecuteNonQuery();
                con.Close();
                Session["Name"] = Name;
                Session["Type"] = Type;

                blSucceeded = true;
                reply = "User Added Successful";
            }
            return new JsonResult { Data = new { status = blSucceeded, Url="/Test/LoginSuccess", message = reply, JsonRequestBehavior.AllowGet } };
         
   }

Step 3: Now write SQL Query or store procedure as per below snippets

ALTER PROCEDURE [dbo].[SP_Emp]
@Empid int=null,
@Name varchar(50)=null,
@Comp varchar(50)=null,
@Type varchar(50)=null,
@Password varchar(50)=null,
@Query varchar(50)

AS
if(@Query='Insert')
BEGIN
   insert into tbl_user values(@Name,@Comp,@Type,@Password);
END

if(@Query='UCheck')
BEGIN
  select Name from tbl_user where Name=@Name;
END
       

Step 4 : Add below Jquery code to header of page, this code contains ajax call to call controller action method and check user availability and add user if user not exist.

<script>
    function Data() {
        var ct = document.getElementById('dp');
        var Type = ct.options[ct.selectedIndex].text;
        var Name = $("#Name").val();
        var Comp = $("#Comp").val();
        var Password = $("#Password").val();

        $.ajax({
            url: '@Url.Action("Insert")',
            data: { Name: Name, Comp: Comp, Password: Password, Type: Type },
            type: 'POST',
            dataType: 'json',
            success: function (result) {             
                if (result.status) {
                    alert(result.message);
                    window.location.href = result.Url;
                }
                else {
                    alert(result.message);                 
                }
            }
        });
    }
</script>

Now try with above code snippets and if you have query regarding above code snippets,then feel free to comment in below comment box.

SEE MORE

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *