In this article I will explain with an example, how to configure
jQuery AutoComplete select (multiple words) in ASP.Net Web Services.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Web Service
The following Web Services consists of a
GetCustomers method which is called using
jQuery AJAX.
The SELECT query gets the Name and the ID of the customer that matches with the prefix text.
The fetched records are processed and the Key Value Pair is created by appending the ID to the Name field in the following format {0}-{1} where the {0} is Name and {1} is the ID.
Since
jQuery AutoComplete will allow to select multiple options, hence we will need to take precautions that the selected customers are excluded from the new search.
To accomplish this functionality, I have made use of an array which stores the terms to be excluded.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Services;
using System.Web.Services;
/// <summary>
/// Summary description forServiceCS
/// </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 ServiceCS : System.Web.Services.WebService
{
public ServiceCS()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetCustomers(string prefix)
{
List<string> terms = prefix.Split(',').ToList();
terms = terms.Select(s => s.Trim()).ToList();
//Extract the term to be searched from the list
string searchTerm = terms.LastOrDefault().ToString().Trim();
//Return if Search Term is empty
if (string.IsNullOrEmpty(searchTerm))
{
return new string[0];
}
//Populate the terms that need to be filtered out
List<string>excludeTerms = new List<string>();
if (terms.Count > 1)
{
terms.RemoveAt(terms.Count - 1);
excludeTerms = terms;
}
string sql = "SELECT ContactName, CustomerId FROM Customers WHERE ContactName LIKE @SearchText + '%'";
//Filter out the existing searched items
if (excludeTerms.Count > 0)
{
sql += string.Format(" AND ContactName NOT IN ({0})", string.Join(",", excludeTerms.Select(s => "'" + s + "'").ToArray()));
}
List<string> customers = new List<string>();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@SearchText",searchTerm);
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}-{1}", sdr["ContactName"], sdr["CustomerId"]));
}
}
con.Close();
}
return customers.ToArray();
}
}
}
VB.Net
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
Imports System.Web.Script.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 ServiceVB
Inherits System.Web.Services.WebService
<WebMethod>
<ScriptMethod(ResponseFormat:= ResponseFormat.Json)>
Public Function GetCustomers(ByVal prefix As String) As String()
Dim terms As List(Of String) = prefix.Split(","c).ToList()
terms = terms.Select(Function(s)s.Trim()).ToList()
'Extract the term to be searched from the list
Dim searchTerm As String = terms.LastOrDefault().ToString().Trim()
'Return if Search Term is empty
If String.IsNullOrEmpty(searchTerm)Then
Return New String(-1) {}
End If
'Populate the terms that need to be filtered out
Dim excludeTerms As List(Of String) = New List(Of String)()
If terms.Count > 1 Then
terms.RemoveAt(terms.Count - 1)
excludeTerms = terms
End If
Dim sql As String = "SELECT ContactName, CustomerId FROM Customers WHERE ContactName LIKE @SearchText + '%'"
'Filter out the existing searched items
If excludeTerms.Count > 0 Then
sql += String.Format(" AND ContactName NOT IN ({0})", String.Join(",", excludeTerms.Select(Function(s) "'" & s & "'").ToArray()))
End If
Dim customers As List(Of String) = New List(Of String)()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("@SearchText", searchTerm)
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
customers.Add(String.Format("{0}-{1}", sdr("ContactName"), sdr("CustomerId")))
End While
End Using
con.Close()
End Using
Return customers.ToArray()
End Using
End Function
End Class
HTML Markup
The HTML Markup consists of following controls:
TextBox – For capturing user input.
HiddenField – For storing ID of the selected customer.
Button – For displaying Name and ID of the selected customer.
The Button has been assigned with an OnClick event handler.
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:HiddenField ID="hfCustomerId" runat="server" />
<br /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" />
Sending TextBox value to Web Services using jQuery AJAX
jQuery AutoComplete Plugin implementation
Inside the HTML, the following
jQuery UI CSS file is inherited.
1. jquery-ui.css
And then, the following
jQuery and
jQuery UI script files are inherited.
1. jquery.min.js
2. jquery-ui.js
Inside the
jQuery document ready event handler, the input TextBox has been applied with the
jQuery AutoComplete plugin.
The
jQuery AutoComplete plugin has been assigned with the following properties and functions.
Properties:
minLength – For setting minimum character length needed for suggestions to be rendered. Here it is set to 1.
Functions:
source – Inside this function, a
jQuery AJAX call is made to the API which acts as a source of data to the
jQuery AutoComplete.
The data received from the API is processed inside the
jQuery AJAX call
Success event handler and
Name and
ID of the customer are set into label and value properties respectively.
select – This event handler is called when an option is selected from the suggestions.
Inside this event handler, the ID of the selected customer is stored into a HiddenField.
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("[id*= txtSearch]").autocomplete({
source:function (request, response) {
$.ajax({
url: '<%= ResolveUrl("~/ServiceCS.asmx/GetCustomers")%>',
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);
}
});
},
select: function (e, i) {
var text = this.value.split(/,\s*/);
text.pop();
text.push(i.item.value);
text.push("");
this.value = text.jo in(", ");
var value = $("[id*= hfCustomerId]").val().split(/,\s*/);
value.pop();
value.push(i.item.val);
value.push("");
$("[id*= hfCustomerId]")[0].value = value.jo in(", ");
return false;
},
minLength: 1
});
});
</script>
Displaying Name and CustomerId of selected customer using JavaScript
When the
Submit Button is clicked, the name of customers selected in the TextBox along with their IDs are displayed in
JavaScript Alert Message Box using
RegisterStartupScript method.
C#
protected void Submit(object sender, EventArgs e)
{
string customerNames = Request.Form[txtSearch.UniqueID].Trim().TrimEnd(new char[] { ',' });
string customerIds = Request.Form[hfCustomerId.UniqueID].Trim().TrimEnd(new char[] { ',' });
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Customer Names: " + customerNames + "\\nCustomerIDs: " + customerIds + "');", true);
}
VB.Net
Protected Sub Submit(ByVal sender As Object, ByVal e As EventArgs)
Dim customerNames As String = Request.Form(txtSearch.UniqueID).Trim().TrimEnd(New Char() {","c})
Dim customerIds As String = Request.Form(hfCustomerId.UniqueID).Trim().TrimEnd(New Char() {","c})
ClientScript.RegisterStartupScript(Me.[GetType](), "alert", "alert('Customer Names: " & customerNames & "\nCustomerIDs: " & customerIds & "');", True)
End Sub
Screenshot
Demo
Downloads