In this article I will explain how to implement jquery autocomplete textbox with webservice in asp.net.
In previous articles I explained JQuery autocomplete textbox example, Ajax autocomplete extender example and many articles in JQuery using asp.net. In previous explained JQuery autocomplete textbox sample article I used page methods directly calling from the page because of that it’s not possible to use that automcomplete functionality in master pages. We can solve this problem by create webservice and use that service to get data from database in asp.net.
To implement this concept first we need to design table in database to save user details in database.
Column Name
|
Data Type
|
Allow Nulls
|
UserId
|
int(set
identity property=true)
|
No
|
UserName
|
varchar(50)
|
Yes
|
Location
|
nvarchar(max)
|
Yes
|
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AutoComplete Textbox with webservice using jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"
rel="stylesheet"
type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function(request,
response) {
$.ajax({
type: "POST",
contentType: "application/json;
charset=utf-8",
url: "AutoCompleteService.asmx/GetAutoCompleteData",
data: "{'username':'"
+ document.getElementById('txtSearch').value
+ "'}",
dataType: "json",
success: function(data)
{
response(data.d);
},
error: function(result)
{
alert("Error");
}
});
}
});
}
</script>
</head>
<body>
<form id="form1"
runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter
UserName: </label>
<input type="text" id="txtSearch" class="autosuggest" />
</div>
</form>
</body>
</html>
|
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
/// <summary>
/// Summary description for AutoCompleteService
/// </summary>
[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 AutoCompleteService : System.Web.Services.WebService {
[WebMethod]
public List<string> GetAutoCompleteData(string username)
{
List<string>
result = new List<string>();
using (SqlConnection
con = new SqlConnection("Data Source=SureshDasari;Integrated
Security=true;Initial Catalog=MySampleDB"))
{
using (SqlCommand
cmd = new SqlCommand("select DISTINCT UserName from UserInformation
where UserName LIKE '%'+@SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("@SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
return result;
}
}
}
}
|
Imports System.Collections.Generic
Imports System.Data.SqlClient
Imports System.Web.Services
''' <summary>
''' Summary description for
AutoCompleteService
''' </summary>
' To allow this Web Service to be
called from script, using ASP.NET AJAX, uncomment the following line.
<WebService([Namespace]:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
_
<System.Web.Script.Services.ScriptService()>
_
Public Class
AutoCompleteService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function
GetAutoCompleteData(ByVal username As String) As List(Of String)
Dim result As New List(Of String)()
Using con As New SqlConnection("Data
Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
Using cmd As New SqlCommand("select
DISTINCT UserName from UserInformation where UserName LIKE
'%'+@SearchText+'%'", con)
con.Open()
cmd.Parameters.AddWithValue("@SearchText", username)
Dim dr As SqlDataReader =
cmd.ExecuteReader()
While dr.Read()
result.Add(dr("UserName").ToString())
End While
Return result
End Using
End Using
End Function
End Class
|
|
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
Subscribe by RSS
Subscribe by Email
|
|||
|
|



Subscribe by RSS
Subscribe by Email
20 comments :
Nice and simple
Bingo worked like charm.thanks
For me its getting error in alertbox... can any one help me out?
Here is ASPX my code
$(document).ready(function() {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteService.asmx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
}
});
}
Webservice Code:
public List GetAutoCompleteData(string username)
{
List result = new List();
using (SqlConnection con = new SqlConnection(@"Data Source=KMC-MNC-2\SQLEXPRESS;User Id=rakesh;Password=kmc;Initial Catalog=EDMS_Login"))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Username from Username where Username LIKE '%'+@SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("@SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
return result;
}
}
}
Superrrr super no words to say
it giving error like could not create type 'webservices'
help me
Hi..
This code is working absolutely fine with Normal asp.net page. But once using master page it is giving me an error (Object required) on script part i.e $.ajax({
Hi Again,
Master page problem resolved. When we are using materpage control Id of a control gets change automatically. Hence change the name of control in the code. E.g.:
data: "{'pre':'" + document.getElementById('ctl00_ContentPlaceHolder1_txtSearch').value + "'}",
hi sir
... I want Auto completed text Box value using 3-tier architecture.. Please help me any one .. immediately ...
how to provide scroll bar for list of items?
Sir please Guide me how to implement image slide show using jquery and web services(jquery with web services).
Hi Sir,
I am getting the following error in the master pagecan u help me out to fix this.
Error-Microsoft JScript runtime error: Object required
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteService.asmx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
If you are still getting alert error then uncomment the line above class in web service.....as below....
//[System.Web.Script.Services.ScriptService]
uncomment this and then will not throw error....
Thanks alot........So simple as to understand easily..Its working fine for me...Keep posting..
Shows Error...
you helped so much, thnx
post the code with master page
post the code if it is placed in master page
if it is throwing error check you code in web service and check the control id's carefully
if you are using master pages the control id will be changing into a combination of you master page content place holder id and control id like "ContentPlaceHolder1_TextBox1"
Hello sir,
Can you help me on this,
I have a grid view ,
For each row , the product text box should be auto complete.
How can i implement this?
I have verified above criteria. Not working in Grid view. other than grid its working fine
Please help me