如何在自动完成中将文本附加到项的现有值中
本文关键字:文本 | 更新日期: 2023-09-27 18:20:17
在自动完成中,我想在结果中附加文本例如:如果我在文本框中键入MU,那么我会得到像MUMBAI、MUBRA这样的结果但在这个结果中,我想展示MUMABI出租,MUMBAI出售,MUMBRA出租,待售的MUBRA。所以在自动完成中,我如何显示上面的结果?
source: function (request, response) {
$.ajax({
type: "POST",
url: "/Homepage/Default.aspx/GetKeywordSearchResults",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ keyword: $("[id*='txtSmartSearch']").val(), postingpurposeid: currentSelectedTab }),
success: function (data) {
response($.map(JSON.parse(data.d), function (item) {
return {
value: item.result ,
label: item.result
}
}));
},
failure: FailureHandler
});
},
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>JQuery AutoComplete TextBox Demo</title>
<link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
</head>
<body>
<form id="form1" runat="server">
<div><h1>AutoComplete Textbox</h1>
City:
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
</div>
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtCity").autocomplete({
source: function (request, response) {
var param = { cityName: $('#txtCity').val() };
$.ajax({
url: "Default.aspx/GetCities",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2//minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.
});
});
</script>
</body>
</html>
我在default.aspx中添加了一个WebMethod"GetCities",以便在JQuery Autocomplete 的Source中调用它
[WebMethod]
public static List<string> GetCities(string cityName)
{
List<string> City = new List<string>();
string query = string.Format("SELECT DISTINCT City FROM Customers WHERE City LIKE '%{0}%'", cityName);
//Note: you can configure Connection string in web.config also.
using (SqlConnection con = new SqlConnection(@"Data Source = .'SQLEXPRESS2008R2; initial Catalog = NORTHWND; Integrated Security = true"))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
City.Add(reader.GetString(0));
}
}
}
return City;
}
请参阅此处->http://dotnetcodepress.com/Articles/ASP-dot-net/jquery-ui-autocomplete-textbox-from-database-in-asp-net