Autocomplete textbox using jquery and asp.net web service

Steps to implement autocomplete textbox in an asp.net webforms application using jQuery and asp.net web service. 
 
Step 1 : SQL Script to create and populate table tblStudents  
 
Create Table tblStudents
(
 ID int identity primary key,
 Name nvarchar(50),
 Gender nvarchar(20),
 TotalMarks int
)
GO
 
Insert into tblStudents values('Mark Hastings','Male',900)
Insert into tblStudents values('Maria Nicholas','Female',760)
Insert into tblStudents values('John Stenson','Male',980)
Insert into tblStudents values('Rob Gerald','Male',990)
Insert into tblStudents values('Ron Simpson','Male',440)
Insert into tblStudents values('Rad Wicht','Male',320)
Insert into tblStudents values('Julian John','Male',983)
Insert into tblStudents values('James Bynes','Male',720)
Insert into tblStudents values('Mary Ward','Female',870)
Insert into tblStudents values('Michael Niron','Male',680)
 
Step 2 : Create a stored procedure to retrieve employee names 
 
Create proc spGetStudentNames
@term nvarchar(50)
as
Begin
    Select Name from tblStudents where Name like @term + '%'
End
 
Step 3 : Create new asp.net web application project. Name it Demo. 
 
Step 4 : Include a connection string in the web.config file to your database.
<add name="DBCS"
     connectionString="server=.;database=SampleDB;integrated security=SSPI"/>
 
Step 5 : Add a WebService (ASMX) to the project. Name it StudentService.asmx. Copy and paste the following code.  
 
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
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 StudentService : System.Web.Services.WebService
    {
        [WebMethod]
        public List<string> GetStudentNames(string term)
        {
            List<string> listStudentNames = new List<string>();
 
            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spGetStudentNames", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter()
                {
                    ParameterName = "@term",
                    Value = term
                });
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    listStudentNames.Add(rdr["Name"].ToString());
                }
            }
 
            return listStudentNames;
        }
    }
}
 
Step 6 : Download jQuery UI from jqueryui.com. Copy and paste the following files in your project.
a) jquery-ui.js
b) jquery-ui.css
c) images  
 
Step 7 : Add a WebForm to the ASP.NET project. Copy and paste the following HTML and jQuery code.   
 
<%@ Page Language="C#" AutoEventWireup="true"
    CodeBehind="WebForm1.aspx.cs" Inherits="Demo.WebForm1" %>
 
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-1.11.2.js"></script>
    <script src="jquery-ui.js"></script>
    <link href="jquery-ui.css" rel="stylesheet" />
    <script type="text/javascript">
        $(document).ready(function () {
            $('#txtName').autocomplete({
                minLength: 2,
                source: function (request, response) {
                    $.ajax({
                        url: 'StudentService.asmx/GetStudentNames',
                        method: 'post',
                        contentType: 'application/json;charset=utf-8',
                        data: JSON.stringify({ term: request.term }),
                        dataType: 'json',
                        success: function (data) {
                            response(data.d);
                        },
                        error: function (err) {
                            alert(err);
                        }
                    });
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        Student Name :
        <asp:TextBox ID="txtName" runat="server">
        </asp:TextBox>
    </form>
</body>
</html>

Comments

  1. Really nice blog post.provided a helpful information.I hope that you will post more updates like this Dot NET Online Training Bangalore

    ReplyDelete

Post a Comment

Popular posts from this blog

Automatically send Birthday email using C#.Net

Drag and Drop multiple File upload using jQuery AJAX in ASP.Net using C# and VB.Net

Difference between each and map in jquery