Wednesday, August 21, 2013

jQuery Autocomplete in an C# Environment with Database

first example:

ASPX - uses codebehind

<script src="js/jquery-1.8.3.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.2.custom.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/jquery-ui.css" />
<script type="text/javascript">

$(function() {
var availableTags = [ <%= SuggestionList %> ];

$( "#<%= TextBox1.ClientID %>" ).autocomplete({
source: availableTags
});
});

</script>

page body

	<form id="form1" runat="server">
<div>
<div class="ui-widget">
<label for="TextBox1">
Tags:
</label>
<asp:TextBox ID="TextBox1" runat="server" />
</div>
</div>
</form>

ASPX codebehind

public string SuggestionList = "";

protected void Page_Load(object sender, EventArgs e) {

string queryString = "SELECT * FROM Customers ORDER BY CompanyName";

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString)) {

using (SqlCommand command = new SqlCommand(queryString, connection)) {

connection.Open();

using (SqlDataReader reader = command.ExecuteReader()) {

while (reader.Read()) {

if (string.IsNullOrEmpty(SuggestionList)) {
SuggestionList += "\"" + reader["CompanyName"].ToString() + "\"";
} else {
SuggestionList += ", \"" + reader["CompanyName"].ToString() + "\"";
}

}
}
}
}

}

second example:

ASPX - uses webservice

	<script src="js/jquery-1.8.3.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>
<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
<asp:PlaceHolder runat="server" id="phSearchText">
<script type="text/javascript">
$(document).ready(function () {

SearchText();

function SearchText() {
$("#<%=TextBox1.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "EmployeeList.asmx/GetAutoCompleteData",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'txt' : '" + $("#<%=TextBox1.ClientID %>").val() + "'}",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function (result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
}
});
</script>
</asp:PlaceHolder>

page body

	<form id="form1" runat="server">
<div class="ui-widget">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>

WebService, this happens to use ADO.Net, but you could use pretty much anything as a valid query source

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 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 EmployeeList : System.Web.Services.WebService
{

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<string> GetAutoCompleteData(string txt)
{
// your code to query the database goes here
List<string> result = new List<string>();
string QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ToString();

using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("Select DISTINCT CompanyName as txt from Customers where CompanyName like @SearchText +'%' ", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("@SearchText", txt);
SqlDataReader obj_result = obj_Sqlcommand.ExecuteReader();
while (obj_result.Read())
{
result.Add(obj_result["txt"].ToString().TrimEnd());
}
}
}

return result;
}

}

No comments:

Post a Comment