Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Auto Complete with jQuery Template Plugin and AJAX

4.80/5 (4 votes)
6 Jul 2013CPOL3 min read 40.3K   742  
AutoComplete Texbox with comma separated insertions

Introduction

Here only one thing that needs introduction is jQuery template Plugin. It gives you more power to render dynamic controls at client side with help of JSON data. It is similar to gridview in asp.net wherein you create layout and assign data source to bind data with Eval/Bind annotations. By using this along with $.ajax I am solving an old problem of auto complete textbox. Remember to add jquery.tmpl.js script file to get benefit of templating.  

Background 

As every developer I too got some R&D kind of task related to auto complete textbox. But this time AjaxToolKit was not more helpful because they want to enter multiple values comma separated with help of auto complete. I googled and finally assembled an idea with multiple techniques. However the task is complete but I found something that is very interesting and quiet powerful call Jquey Template plugin.

Workflow

We will use one empty listbox which is hidden initially along with a textbox. When user starts typing in textbox it send $.ajax request to server to find matching suggestings and get return data in JSON format. We use that JSON to bind existing empty listbox with help of tmpl() plugin and make it visible to enable user to select desired input.

How it Works 

Simple as explain in Introduction. We need to have some container that will hold our data similar to gridview.

XML
<script id="tmplSuggestions" type="text/html">
<option>${Name}</option></script> 

First thing - There is just a weird script with an Id that we use later to bind it and type = 'text/html'. So one thing clear from this line that any thing within this tag will be HTML.

Second thing - There is <option> tag that surely going to part of some <select> control. last thing is ${Name} is equivalent to <%#Eval('ColumnName')%>. Yes this column name of your data source.

Now I have one textbox and a listbox on page as described.

XML
<asp:TextBox runat="server" Width="200px" ID="txtnames" 
  autocomplete="off" onkeyup="getsuggestions(event)"></asp:TextBox>

<asp:ListBox runat="server" Width="200px" CssClass="suggestions" 
  Style="display: none;" ID="lbSuggestion" 
  onclick="Selectsugg('mouse',event)" onkeyup="Selectsugg('key',event)">
</asp:ListBox> 

As user types in textbox it makes a lightweight ajax request to server using.

JavaScript
function getsuggestions(event) {

    $.ajax({
        type: "POST",
        url: "AutoCompleteDemo.aspx/getSuggestions", //pagename.aspx/methodname
        data: "{'keyword':'" + keyword + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg, sd, fg) {
        if (msg.d && msg.d.length > 0) {
        $("#" + '<%=lbSuggestion.ClientID%>').show().children().remove();
        //create option element by using "jquery.tmpl.js" 
        //and add them to listbox
        $("#tmplSuggestions").tmpl(msg.d).appendTo("#" + 
          '<%=lbSuggestion.ClientID%>');
        }
        else {
            $("#" + '<%=lbSuggestion.ClientID%>').hide();
            }
        },
        error: function (gfh, ghg) {
            alert("error");
        },
        complete: function (eret, tytyt) {
            //alert("complete");
        }
    });
}

This method calls some WebMethod in your codebehind as

C#
[WebMethod]
public static object getSuggestions(string keyword)
{
    // Getting data into datatable to depict normal scenario, 
    // This is just illustration you can remove following code with yours
    
    DataTable dtSugg = GetSuggestionsFromDB();
    var list = from dr in dtSugg.AsEnumerable()
               where dr.Field<string>("Name").Contains(keyword)
               select new {Name = dr.Field<string>("Name")};
    return list;
} 

Above function takes some keyword entered in textbox and make a search to data base to find suggestion and return data in form of list that is automatic serialize.

OK Now switch back again to that ajax function this has a Success: attribute that called when data successfully returned from server. Now we will bind that data to our listbox using following code

JavaScript
$("#tmplSuggestions").tmpl(msg.d).appendTo("#" + '<%=lbSuggestion.ClientID%>');

Above line is first find element with id = tmplSuggestions. In our case that is <script> block, then it applies .tmpl() plugin by passing msg.d as data. The result of this is now appended to our listbox 'lbSuggestion' . And you are done.

Note that before adding data to listbox we are clearing its old items by using following line

JavaScript
$("#" + '<%=lbSuggestion.ClientID%>').show().children().remove();

Points to note

Nothing more interesting to show on .aspx page.. but wait there is property called EnableEventValidation= "false". As its name suggests it tells the server to not validate event after postback.

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoCompleteDemo.aspx.cs"
    Inherits="AutoCompleteTextBox.AutoCompleteDemp"  EnableEventValidation="false" %> 

Why this- As we are modifying DoM on-fly and server is not in sync with such .net controls. So just to get rid of yellow page error.

As Overall exercise it to get suggestion from server and show to client thus code has some hide/show and other keyboard navigation/handling related code. That for sure can be remove if not suits you.

You can use it to render grid.

XML
<script id="tmpGrid" type="text/html">
<tr>  <td>${Name}</td>  <td>${age}</td>  <td>${salary}</td>  <td>${designation}</td> </tr> 
</script>
<table id="tblData"></table>

$("#tmpGrid").tmpl(msg.d).appendTo("#tblData");  

Simple as that for more in depth details I have made a complete article for above client side gridview implementation.   

Conclusion

Interesting thing I/we learn here is jquery.tmpl.js and $.ajax call. please explore it for more fun.

Folks, the world is open to tweak, Hence this code too. Please make it more usable/optimize/relavant as per your requirement.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)