Tuesday, September 25, 2012

AutoCompleteExtender – AJAX Control

 

Introduction :

It is a feature that helps end user when typing for a word in a search box. We can say Google Search box as live example for this. When we start typing “java” in the search box , it gives a list of all searches (that we made earlier or other user had made ) containing “Java” as prefix. Now a days this feature is available in almost all the search engine sites.

This feature extends the functionality of the textbox.

Important attributes of this control , that needs to be specified are

TargetControlID : Textbox ID to which autocomplete functionality needs to be added.

ServiceMethod : Functions which fetches data based on the  text (takes prefix) typed in the database.

Example – AutoCompleteExtender :

Step 1 : Register AjaxControlToolkit.

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>

Step 2 : Add ToolKitScriptManager to the page.



<ajaxToolkit:ToolkitScriptManager ID="Sc1" runat="server">
</ajaxToolkit:ToolkitScriptManager>

Step 3: Add textbox and AutoCompleteExtender to the page. Assign textbox ID to “TargetControlID” attribute. Define some SeriveMethod and set “EnableCaching” to true.


If we set “EnableCaching” to true , then no need to define any functionality for ServiceMethod . Whatever user types in the textbox will be shown as autocomplete text. Suppose say user first types “aa” and submits  and next when he start typing a , it will show “aa” as a dropdown list under the textbox.



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoComplete Extender</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<ajaxToolkit:ToolkitScriptManager ID="Sc1" runat="server">
</ajaxToolkit:ToolkitScriptManager>
Enter some text:<asp:TextBox ID="txtdata" runat="server">
</asp:TextBox>
<br /> <br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
<asp:Button ID="btnClear" runat="server" Text="Clear" OnClick="btnClear_Click"/>
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1"
runat="server" TargetControlID="txtdata"
ServiceMethod="DisplayText"
EnableCaching="true" >
</ajaxToolkit:AutoCompleteExtender>
</div>
</form>
</body>
</html>


 protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Write("Page is Submitted");

}
protected void btnClear_Click(object sender, EventArgs e)
{
txtdata.Text = "";

}

public string[] DisplayText(string PrefixText, int Count, string ContextKey)
{
return new string[] { string.Empty };
}

Output :


AutoCompleteExtender_Op1


AutoCompleteExtender_Op2

No comments:

Post a Comment