Monday, October 15, 2012

AJAX Control ToolKit Tutorial AutoComplete Extender Using ASP.NET 4.0 and C#

Welcome to another AJAX tutorial, today we will be talking about the AutoComplete Extender that ships with the ASP.NET AJAX Control tool kit.

Autocomplete , great concept used by thousands of websites and social networks. We take this AJAX control for granted, you have used quite frequently actually… as a matter of fact it’s used by 500 million people daily and you used it to search for an image or a term on Google, just like you found this Tutorial.
We used over 10 web hosting companies before we found Server Intellect . Our new server with cloud hosting ,was set up in less than 24 hours. We were able to confirm our order over the phone. They responded to our inquiries within an hour. Server Intellect’s customer support and assistance are the best we’ve ever experienced.
Here is a preview of what are going to build today.

undefined
With magic like abilities , this extender knows the future, it sees it; i think it has clairvoyant powers.

Well we like our audience to think that our websites are pure magic and illusions, but in reality all that we are doing is using a simple web service to grab the information from the text input and parsing it out in our database and using the AutoComplete extender to return the results in real time to our TextBox .

So let’s begin building our Autocomplete extender.

  1. Let’s start by adding a new WebForm to this project and name it AutoComplete.aspx.
  2. Before you can even use the AJAX Control Toolkit, you must add a ToolScriptManager to the page. You can do this 2 ways, you can both Drag and Drop the ToolScriptManager or by type the control in source mode. Below is the markup.
      <cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </cc1:ToolkitScriptManager>
    














  • Now add a textbox to your form.

  • <asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />











  • Next is up is adding the AutoCompleteExtender, You can drag & drop this from the toolbox. Or click on the Tab to the right on the ASP TextBox you just added. We used over 10 web hosting companies before we found Server Intellect . They offer dedicated servers , and they now offer cloud hosting !

  •  <cc1:AutoCompleteExtender runat="server" BehaviorID="AutoCompleteEx" ID="autoComplete1"
                TargetControlID="myTextBox"
    









  • Now remember to set the TargetControls and name your TextBox to something you will remember for styling the Extender. As a matter of fact here is our Styles for the Extender.

  •  <style>
            /*AutoComplete flyout */
            
            .autocomplete_completionListElement
            {
                margin: 0px !important;
                background-color: inherit;
                color: windowtext;
                border: buttonshadow;
                border-width: 1px;
                border-style: solid;
                cursor: 'default';
                overflow: auto;
                height: 200px;
                text-align: left;
                list-style-type: none;
            }
        </style>
    







  • So look at this, we have our extender attached to our textbox, now we have to control what is shown and how it will be shown. We will have to provide the Service Path, Give it the Target ID to control, set the minimum prefix length that it will start suggesting. You will also notice that we set an animation sequence to display and we set it to find, the AutoComplete Extender.

  •  <cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
            </cc1:ToolkitScriptManager>
            <b>AutoComplete Demonstration</b><br />
            Type some characters in this textbox. The web service returns random words that
            start with the text you have typed.
            <br />
            <br />
            <asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
            <cc1:AutoCompleteExtender runat="server" BehaviorID="AutoCompleteEx" ID="autoComplete1"
                TargetControlID="myTextBox" ServicePath="~/AutoComplete.asmx" ServiceMethod="GetCompletionList"
                MinimumPrefixLength="2" CompletionInterval="1000" EnableCaching="true" CompletionSetCount="20"
                CompletionListCssClass="autocomplete_completionListElement" CompletionListItemCssClass="autocomplete_listItem"
                CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem" DelimiterCharacters=";, :"
                ShowOnlyCurrentWordInCompletionListItem="true">
                <Animations>
                <OnShow>
                    <Sequence>
                            
                        <OpacityAction Opacity="0" />
                        <HideAction Visible="true" />
                                
                               
                        <ScriptAction Script="
                            // Cache the size and setup the initial size
                            var behavior = $findundefined'AutoCompleteEx');
                            if undefined!behavior._height) {
                                var target = behavior.get_completionListundefined);
                                behavior._height = target.offsetHeight - 2;
                                target.style.height = '0px';
                            }" />
                                
                        <%-- Expand from 0px to the appropriate size while fading in --%>
                        <Parallel Duration=".4">
                            <FadeIn />
                            <Length PropertyKey="height" StartValue="0" EndValueScript="$findundefined'AutoCompleteEx')._height" />
                        </Parallel>
                    </Sequence>
                </OnShow>
                <OnHide>
                    <%-- Collapse down to 0px and fade out --%>
                    <Parallel Duration=".4">
                        <FadeOut />
                        <Length PropertyKey="height" StartValueScript="$findundefined'AutoCompleteEx')._height" EndValue="0" />
                    </Parallel>
                </OnHide>
                </Animations>
            </cc1:AutoCompleteExtender>
            <script type="text/javascript">
                // Work around browser behavior of "auto-submitting" simple forms
                var frm = document.getElementByIdundefined"aspnetForm");
                if undefinedfrm) {
                    frm.onsubmit = function undefined) { return false; };
                }
            </script>
            <%-- Prevents the user from hitting Enter to start a collapsible Panel --%>
            <input type="submit" style="display: none;" />
    





  • So now that we have our Front end built let’s create our web service method.

  • WebServiceundefinedNamespace = "http://tempuri.org/")]
    [WebServiceBindingundefinedConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]
    public class AutoComplete : WebService
    {
        public AutoCompleteundefined)
        {
        }
     
        [WebMethod]
        public string[] GetCompletionListundefinedstring prefixText, int count)
        {
            if undefinedcount == 0)
            {
                count = 10;
            }
     
            if undefinedprefixText.Equalsundefined"xyz"))
            {
                return new string[0];
            }
     
            Random random = new Randomundefined);
            List<string> items = new List<string>undefinedcount);
            for undefinedint i = 0; i < count; i++)
            {
                char c1 = undefinedchar)random.Nextundefined65, 90);
                char c2 = undefinedchar)random.Nextundefined97, 122);
                char c3 = undefinedchar)random.Nextundefined97, 122);
     
                items.AddundefinedprefixText + c1 + c2 + c3);
            }
     
            return items.ToArrayundefined);
        }
    }
    
    



  • So let’s explain what this is really doing. So our Method GetCompletionList checks for the prefixText that we set to a minimum of two. Since we are not using a database and we are really showing you how the AutoComplete Extender works we will return a Random sequence of characters.

  • Conclusion

    As you can see above, it’s a regular TextBox until you start typing in a word and it begins to find a matching statement or word.
    Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.
    Now this can be configured many different ways, for example, if you only wanted the web service method to search a database for first names and only return examples from a specific list of first names, or by matching zip codes or only last names.

    The possibilities are endless; you can even style your list to look like Facebook or a Google Style Auto suggest.

    Thank you for reading our tutorial on AJAX Controls, we aim to provide the best AJAX tutorials. Learning AJAX in ASP.NET is easy and we hope you are getting your hands dirty by trying different things and coming up with your own ideas. If you have any questions or concerns, please feel free to suggest a tutorial or you can comment below in the comments section.