页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyfirstAutocomplayte.aspx.cs" Inherits="autocomplete_MyfirstAutocomplayte" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<script type="text/javascript" src="jquery-autocomplete/lib/jquery.js"></script>
<script type='text/javascript' src='jquery-autocomplete/jquery.autocomplete.js'></script>
<!--
<link rel="stylesheet" type="text/css" href="jquery-autocomplete/demo/main.css" />
--> <link rel="stylesheet" type="text/css" href="jquery-autocomplete/jquery.autocomplete.css" />
<!-- <link rel="stylesheet" type="text/css" href="jquery-autocomplete/lib/thickbox.css" />
-->
<script type="text/javascript">
$().ready(function(){
$("#txtRealName").autocomplete("AutoName.aspx",{
delay: 10,
minChars: 1,
matchSubset: 1,
matchContains: 1,
cacheLength: 10,
onItemSelect: selectItem,
onFindValue: findValue,
formatItem: formatItem,
autoFill: true
});
$("#txtRealName").result(findValueCallback);//加这个主要是联动显示id
});
function findValue(li) {
if( li == null ) return alert("No match!");
// if coming from an AJAX call, let's use the CityId as the value
if( !!li.extra ) var sValue = li.extra[0];
// otherwise, let's just display the value in the text box
else var sValue = li.selectValue;
//alert("The value you selected was: " + sValue);
}
function selectItem(li) {
findValue(li);
}
function formatItem(row) {
return row[0];
//return row[0] + " (id: " + row[1] + ")"
//如果有其他参数调用row[1],对应输出格式Sparta|896
}
// function lookupAjax() {
// var oSuggest = $("#txtRealName")[0].autocompleter;
// oSuggest.findValue();
// return false;
// }
function findValueCallback(event, data, formatted) {
$("#lbfindId").html(data[1]);//使用“|”分割后的第二个属性[对应=>如果有其他参数调用row[1],对应输出格式Sparta|896]
//$("#lbfindId").html(formatted);//textbox选择的值
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtRealName" runat="server"></asp:TextBox>
<label id="lbfindId"></label>
</div>
</form>
</body>
</html>
代码:
public partial class autocomplete_AutoName : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (Request.QueryString["q"] != null && Request.QueryString["q"] != "")
{
Response.Clear(); Response.Charset = "utf-8";
Response.Buffer = true;
this.EnableViewState = false;
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "text/plain";
Response.Write(GetLikeUserName(Request.QueryString["q"]));
Response.Flush();
Response.Close();
Response.End();
}
}
}
private String GetLikeUserName(String namestr)
{
DataTable dt = Northwind.GetOrders(namestr); //后台获取的数据。
StringBuilder sbstr = new StringBuilder();
for (int i = 0; i < dt.Rows.Count; i++)
{
sbstr.Append(dt.Rows[i]["shipname"].ToString() + "|" + dt.Rows[i]["orderid"].ToString());
sbstr.Append("\n");
}
return sbstr.ToString();
}
}
就这么简单就ok了!