我使用以下asp.net和C#代码完成了Ajax工具包自动完成工作。
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
Search our Languages: <asp:TextBox ID="txtLanguage" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txtLanguage" MinimumPrefixLength="1"
ServiceMethod="GetCompletionList" UseContextKey="True">
</asp:AutoCompleteExtender>
<br />
<br />
<asp:Button ID="btnAddSelected" runat="server" Text="Add to chosen Languages >"
onclick="btnAddSelected_Click" />
<br />
<br />
<asp:Label ID="lblSelectedLanguages" runat="server" Text=""></asp:Label>
</div>
</form>
这是我的代码隐藏C#:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
// Create array of languages.
string[] languages = { "Afrikaans", "Albanian", "Amharic", "Arabic", "Azerbaijani", "Basque", "Belarusian", "Bengali", "Bosnian", "Bulgarian" };
// Return matching languages.
return (from l in languages where l.StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) select l).Take(count).ToArray();
}
protected void btnAddSelected_Click(object sender, EventArgs e)
{
lblSelectedLanguages.Text += txtLanguage.Text += ", ";
}
单击按钮时,所选语言将添加到标签中,但我想删除该按钮,并使用Ajax工具包中的部分回发自动将自动完成中的选定项添加到标签中。
有人可以告诉我如何实现这个目标吗?
感谢。
答案 0 :(得分:3)
OnClientItemSelected
以运行javascript函数<强> ASPX:强>
<head runat="server">
<title></title>
<script type="text/javascript">
function ItemSelected(sender, args) {
__doPostBack(sender.get_element().name, "");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
Search our Languages:
<asp:TextBox ID="txtLanguage" autocomplete="off" runat="server" OnTextChanged="TextChanged" />
<asp:AutoCompleteExtender OnClientItemSelected="ItemSelected" ID="AutoCompleteExtender1"
runat="server" TargetControlID="txtLanguage" MinimumPrefixLength="1" ServiceMethod="GetCompletionList"
UseContextKey="True">
</asp:AutoCompleteExtender>
<br />
<asp:Label ID="lblSelectedLanguages" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
代码背后:
protected void TextChanged(object sender, EventArgs e)
{
lblSelectedLanguages.Text += txtLanguage.Text += ", ";
}
答案 1 :(得分:0)
看起来你只需要挂钩文本框的on text changed事件,然后将你的逻辑放在代码benind中。这样的事情
标记
<asp:TextBox ID="txtLanguage" OnTextChanged="txtLanguage_textChanged" AutoPostback="true" />
然后在你的代码中
protected void txtLanguage_textChanged(object sender, EventArgs e)
{
//use the retrieved text the way you like
lblSelectedLanguages.Text =txtLanguage.Text;
}
希望这会有所帮助。我还建议您尝试查看JQuery自动完成小部件。它给我带来了纯粹的快乐,我确实离婚了自动完成扩展程序。 Jquery Autocomplete