Multi-value jQuery AutoComplete in ASP.NET

There are many situations where while using autocomplete feature on textbox we need to show additional information to users like one of Google suggestion shown in picture below:

In this screenshot along with suggestions user is getting a URL for Facebook site.

We will develop this with jQuery and ASP.NET web service(.asmx) and will use JSON (JavaScript Object Notation) format to pass list of our class object which will contain not one but as many as you want values to help users make decision as to which option they should select.

In this article we will first download latest version of jQuery from www.jQuery.com website (If you are using Visual Studio 2010 then you can skip this step as ASP.NET website already come with jQuery scripts installed under scripts folder of any website you create using ASP.NET website template in VS2010).

After downloading jQuery scripts we will need to download jQuery UI script files from http://jqueryui.com/download here you have two options:

  1. Download default library which include all components available in jQuery UI
  2. Customize your download based on your need (in this case make sure you have "Autocomplete" option selected under "Widgets")

Once you have downloaded these scripts we will get into the development for our multi value suggestion textbox.

To get started create new website and add all downloaded scripts to your newly created website.

We will add a class to this project in order to  return results as List using JSON, for this right click on App_Code folder and add a new class, name that class as "CityCountry.cs". We will use this class to create three properties one for each City, State, and Country. After adding these properties your code should look like this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

public class CityCountry

{

private string _city;

private string _state;

private string _country;

 

public CityCountry()

{

_city = "";

_country = "";

_state = "";

}

 

public string City { get { return _city; } set { _city = value; } }

public string State { get { return _state; } set { _state = value; } }

public string Country { get { return _country; } set { _country = value; } }

}

 

Now we will create a web service (.asmx) to get our data from Adventure works database, so, right click on your website in solution explorer and add a new web service (.asmx) and name it Search.asmx.

After adding web service to your project open Search.cs file from App_Code folder of your website and add following references at the top of your cs file:

 

using System.Data.SqlClient;

using System.Web.Configuration;

 

Now after WebServiceBinding attribute uncomment /add "[System.Web.Script.Services.ScriptService]" attribute, this will make your web service accessible using JavaScript. After these changes your code should look this:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Data.SqlClient;

using System.Web.Configuration;

 

/// <summary>

/// Summary description for Search

/// </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 Search : System.Web.Services.WebService {

 

Now delete helloworld method which is located below "[WebMethod]" attribute then add following code:

[WebMethod]

public List<CityCountry> FetchCity(string prefixText) {

List<CityCountry> collectionCity = new List<CityCountry>();

CityCountry cc;

using (SqlConnection conn = new SqlConnection())

{

conn.ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

using (SqlCommand cmd = new SqlCommand())

{

cmd.CommandText = @"SELECT distinct [City],StateProvince,CountryRegion FROM [Address] where City like @SearchText +'%'";

cmd.Parameters.AddWithValue("@SearchText", prefixText);

cmd.Connection = conn;

conn.Open();

using (SqlDataReader sdr = cmd.ExecuteReader())

{

while (sdr.Read())

{

cc = new CityCountry();

cc.City = sdr["City"].ToString();

cc.Country = sdr["CountryRegion"].ToString();

cc.State = sdr["StateProvince"].ToString();

collectionCity.Add(cc);

}

 

}

conn.Close();

 

}

}

return collectionCity.ToList();

}

 

Now what this code is doing is, it is taking string prefixText, which is in this case will be what we are going to type in the textbox, and web service will return results from adventureworks database after querying distinct City, State and Country from Addess table. After fetching results in SqlDataReader we will create instances of our CityCountry class and after populating City, State, and Country on that object from reader we will add it to our List named collectionCity. This list we will hold all values that are present in SqlDataReader. At the end we will return this collection as List.

This completes our logic to fetch data from database now we will add some jQuery logic on .aspx page to fetch the results and show it to the user.

So open Default.aspx page and add a textbox either from markup or from toolbar and set its ID property to txtCity, after adding textbox your code should look like this:

 

<body>

<form id="form1" runat="server">

<div>

<asp:TextBox runat="server" ID="txtCity" />

</div>

</form>

</body>

 

 

That's it for the markup now we will add reference of our scripts to the head section of the page and start writing some JavaScript to get results back:

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>

<script src="Scripts/jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>

<link href="styles/jquery-ui-1.8.5.custom.css" rel="stylesheet" type="text/css" />

 

As you can see I have added three references in which first one is jQuery reference, second is jQuery UI reference, and third is the default css file that you get when you download jQuery UI from jQuery UI website.

Once references have been added we will use jQuery to find txtCity textbox on the page and add autoComplete event on the textbox.

AutoComplete we will define URL of the web service from which we are expecting results back to our page along with its dataType, type of request we are sending, expected content-Type in response and data that we are passing from textbox.

We will use success attribute to write a function which will read the response from web service and format its label property for display and value property for selected value.

So we will add following JavaScript code to show results back from our web service:

<script type="text/javascript">

$(document).ready(

function () {

$('#txtCity').autocomplete(

{

source: function (request, response) {

$.ajax({

 

url: "Search.asmx/FetchCity",

dataType: "json",

type: "POST",

contentType: "application/json",

data: "{ 'prefixText': '" + request.term + "' }",

// dataFilter: function (data) { return data; },

success: function (data) {

response($.map(data.d, function (item) {

return {

label: item.City + ", " + item.Country,

value: item.City

}

}));

},

 

error: function (XMLHttpRequest, textStatus, errorThrown) {

alert(errorThrown);

}

 

});

}, minLength: 1

});

});

</script>

 

Now run the website to view page in the browser and type "ne" in the textbox provided, you should see your autocomplete with multiple value working:

Thank you.

Tags: , , ,

AJAX | ASP.NET | jQuery