Tuesday, 6 September 2011

Autocomplete using JQuery in ASP.net

This article describes how to use jQuery AutoComplete plug-in. Auto-complete takes input from the user, and returns a list of words that match the users input.
You could download jQuery AutoComplete plug-in from the following link:
First create input control like:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
  </asp:Content>


 Add references like:
    <link href="Styles/jquery-ui.css" rel="stylesheet" type="text/css" />
    <link href="Styles/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.6.2.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui.js" type="text/javascript"></script>
    <script src="Scripts/jquery.autocomplete.js" type="text/javascript"></script>
    <script src="Scripts/jquery.autocomplete.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.autocomplete.pack.js" type="text/javascript"></script>

Then provide options in autocomplete as below:
      $("#<%=txtSearch.ClientID%>").autocomplete({
            source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
        });

Now this is ready to work. However, this is not case every time. We might need to call server side functions to get options. In that case this can be achieved by calling function from server side through  a web handler. I have created a web handler named "select.ashx" and calling this from autocomplete as below.
$("#<%=txtSearch.ClientID%>").autocomplete('select.ashx');

A web handler code will look like:
public class select : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (!String.IsNullOrEmpty(context.Request.QueryString["q"]))
            {
                foreach (string s in GetAutoCompleteValues(context.Request.QueryString["q"]))
                {
                    context.Response.Write(s + Environment.NewLine);
                }
            }
        }

public static string[] GetAutoCompleteValues(string prefixText)
        {
            List<string> myList = new List<string> { "C#", "F#", "JavaScript", "C++", "Ruby", "Java", "c++", "php", "coldfusion", "asp", "VB" };
            List<string> autoCompleteList = new List<string>();

            foreach (string s in myList)
            {
                if (s.ToUpper().Contains(prefixText.ToUpper()))
                {
                    autoCompleteList.Add(s);
                }
            }
            return autoCompleteList.ToArray();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

Now, autocomplete will look like as below:
Autocompletion UI





No comments:

Post a Comment