我们在我所在的公司做类似的事情。为此,我们通过 AJAX 使用 Web 服务。
本质上,您使用 AJAX AutoCompleteExtender (ACE) 修改标准文本框。这个 ace 引用了一个 Web 服务(我将对此进行说明),该服务会即时获取客户输入的信息。一旦启动并运行,它就非常酷。
这是一个例子:
.ascx
<asp:TextBox ID="txtInsuranceCompany" runat="server" TabIndex="520"
AutoComplete="Off"AutoCompleteType="Disabled" CssClass="asbSearch" Width="350px"></asp:TextBox>
<ajax:AutoCompleteExtender ID="aceInsuranceCompany" runat="server" CompletionSetCount="20"
MinimumPrefixLength="0" OnClientShown="resetPosition" ServiceMethod="LookupData"
ServicePath="~/WebLookUpService.asmx" TargetControlID="txtInsuranceCompany" UseContextKey="true">
</ajax:AutoCompleteExtender>
微妙的是,您必须确保为您的自动完成扩展器设置上下文键,并在您的 Web 服务中创建一些功能来加载您的值(我将再次说明)。
.vb 代码隐藏
Dim yourhardcodedlist As New List(Of String)
yourhardcodedlist.Add("Progressive")
yourhardcodedlist.Add("State Farm")
yourhardcodedlist.Add("USAA")
WebLookUpService.AddLookupValues(txtInsuranceCompany.ID, yourhardcodedlist.ToArray)
aceInsuranceCompany.ContextKey = public_var0 & ":" & public_var1 & ":" & txtInsuranceCompany.ID
请注意,“public_var0”“和 public_var1”不是强制性的。这只是说明如何将更多信息传递给您的 Web 服务,而无需实际将其作为参数传递(即一个冒号分隔的列表,您的 Web 服务函数可以解析出来以用于 SQL 语句或其他内容)。
现在对于网络服务...(.asmx)
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<System.Web.Script.Services.ScriptService()> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebLookUpService
Inherits System.Web.Services.WebService
<System.Web.Services.WebMethod(), System.Web.Script.Services.ScriptMethod()> _
Public Function LookupData(ByVal prefixText As String, ByVal count As Integer, ByVal contextKey As String) As String()
'Construct SQL statement to pull from database
'parsing the context key as necessary to construct your SQL statement (if necessary)
'Dim somethingForSql As String = contextKey.Split(":")
Dim suggestions As List(Of String) = New List(Of String)
Try
Using cnADO As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("PublicSafetyServer").ToString)
cnADO.Open()
Dim dt As DataTable = New DataTable
Dim da As New SqlDataAdapter
da.SelectCommand = New SqlCommand("<YourSQLStatement>")
da.Fill(dt)
Dim endRow As Integer = dt.Rows.Count
If endRow > count Then
endRow = count
End If
For i As Integer = 0 To endRow - 1
Dim des As String = dt.Rows(i).Item(field)
Dim val As String = dt.Rows(i).Item(field)
suggestions.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(des, val))
Next
End Using
Catch ex As Exception
'Throw Error
End Try
suggestions.Sort()
If suggestions.Count = 0 Then
suggestions.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(noneFound, ""))
End If
Return suggestions.ToArray()
End Function
很酷的是,您可以通过“您的硬编码列表”故意添加值,该列表将与您通过 Web 服务提取的任何值相结合。这样,如果您无法向数据库添加值,您可以直接添加值。