Introduction:
In this article I will explain how to implement jquery autocomplete textbox with webservice in asp.net.
In this article I will explain how to implement jquery autocomplete textbox with webservice in asp.net.
Description:
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.
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
|
After completion
table design enter some of user details in database to work for our sample.
Once table creation
complete write the following code in aspx page
<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>
|
If
you observe above code in header section I added some of script and css files
by using those files we have a chance to display auto complete text with css
style and I mentioned url field as “AutoCompleteService.asmx/GetAutoCompleteData” this mean we are
calling GetAutoCompleteData method from AutoCompleteService.asmx webservice.
To creat this
webservice right click on your application >> Select Add New Item >> select Web
Service >> Give name of service AutoCompleteService.asmx
and click OK
Once
webservice created open code behind file and write the following code
C# Code
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;
}
}
}
}
|
VB.NET Code
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
|
Demo
Download
sample code attached
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. |
|||
|
|||
40 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
hi.. this code in not working in vb.net giving problem this plz helf
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '+'xzhg'+ '%'' at line 1
I AM USING THIS CODE IN MASTER PAGE BUT THIS CODE IS NOT WORKING PLZ GIVE ME LINK OR FULL CODE AUTOCOMPLITE USE IN MASTERPAGE..
data: "{'pre':'" + document.getElementById('ctl00_ContentPlaceHolder1_txtSearch').value + "'}",
Returned me alert error no matter whatever i tried. Not too sure what went wrong, try to debugging into web services code, but the execution not even yet to break there
I am the same person from no23. If you guys keep on hitting alert error, try this to check what is the error.
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
hi,
will this code work with DNN6
Hi suresh,
Thanks for sharing the nice post. I have followed your previous post also in which you have used WebMethod instead of Web service Just out of curosity I have one doubt which will be more fatser if we compare both the ways i.e. WebMethod or Webservice.
Suresh -
How will it work for mutiple user names(first and last name) i.e with duplicate names?
Very nice post, well explained.
hi it is not working for asp.net text box i.e.
awesome!!!
Please I ve tried it in my index.aspx and it worked fine. But when I tried it in a page in a sub folder, it does not work. Please help me.
how to show the limited values display? limit values =10
If i use textbox with runat="server" ,auto complete textbox is not working....in masterpage
i had done a nearly same coding for auto complete in text box. but it is not working in popup menu of text box. so please help me by giving suggestions.
i had make a break point in vb page. but, page is not transferred to vb page from source.
this is my coding.
function pageLoad(sender, args) {
$(document).ready(function() {
$("#<%=txtitemname.ClientID %>").autocomplete({
source: function(request, response) {
$.ajax({
url: '<%=ResolveUrl("~/spares.asmx/GetSpareList") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
response($.map(data.d, function(item) {
return {
label: item.split('|')[0],
val: item.split('|')[1]
}
}))
},
error: function(response) {
alert(response.responseText);
},
failure: function(response) {
alert(response.responseText);
}
});
},
select: function(e, i) {
$("#<%=hdnitemid.ClientID %>").val(i.item.val);
},
minLength: 1
});
});
}
Love you yaar........... works like a charm.
Thanx a lot.
Hi,
Thank You..!!
Which is working fine in dev environment. But published code not working in production server.
(simply act as textbox) Any changes need to do ??
Suresh
I am new in asp.net I want to create multiple value autocomplete with multiple table and if once value is selected then it should not be selected again also have cross function with values
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'autocomplete'
Help please getting this error.
Note: Only a member of this blog may post a comment.