Ajax Based Multiselect JQuery Autocomplete Control in ASP.Net

In this article i will explain step by step creating Ajax Based Multi select JQuery Autocomplete User Control.

Here, we will use Jquery UI Tool’s Autocomplete Control. To get the Data using AJAX, here we will try Handlers of ASP. Using Handlers against simple asp.net page is that, if we will use ASPX page then it will go through all the phases of page (nearly 1o) whereas Handler is faster than ASPX page.

Ajax Based Multiselect JQuery Autocomplete Control in ASP.Net

Ajax Based Multiselect JQuery Autocomplete Control in ASP.Net

Step 1 : creating Handler

In step 1, we will create the handler which will provide the data in form of JSON. To know more about  creating JSON is C#, read this article written by me on codeproject.

File Name : UsersList.ashx

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace AutoComplete
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UsersList : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string prefixText = context.Request.QueryString["term"];
            //prefixText  is text typed by user to search
            string values = getUsersList(prefixText);
            context.Response.ContentType = "application/json";
            context.Response.Write(values);
        }

        private string getUsersList(string prefixText)
        {
            List<Emp> eList = new List<Emp>();
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            DataTable dtUserPickerData = DataBase.LoadDataForUserPicker(prefixText);
            //Here capacity means number of records shown in AutoComplete
            int capacity = 10;
            int capacityCounter = 0;
            foreach (DataRow dr in dtUserPickerData.Rows)
            {
                if (capacityCounter <= capacity)
                {
                    Emp e = new Emp();
                    e.value = dr[3].ToString();//Ex : jitendra.zaa@xyz.com
                    e.label = dr[0].ToString() + "( " + dr[3].ToString() + " )";//Ex : jitendra Zaa (jitendra.zaa@xyz.com)
                    eList.Add(e);
                    capacityCounter++;
                }
                else
                {
                    break;
                }
            }
            //JsonConvert.SerializeObject() will convert the List into JSON text
            string ans = JsonConvert.SerializeObject(eList);
            return ans;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    class Emp
    {
        private string _name;
        private string _to;

        public string value
        {
            get { return _to; }
            set { _to = value; }
        }
        public string label
        {
            get { return _name; }
            set { _name = value; }
        }

    }
}

The text which you type to search will come as request parameter “term”.
In above code, assume that i am getting the datatable from the database which contains the username and his email id. the return type of the handler is “application/json” which indicates that it is returning JSON object in response.

Step 2 : Creating User Control

In this section we will create a usercontrol in our project.

FileName : AutoComplete.ascx.cs

namespace AutoComplete
{
    public partial class AutoComplete : System.Web.UI.UserControl
    {

        private bool _isMultiLine;

        /// <summary>
        /// Gets or sets a value indicating whether this instance is multi line.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is multi line; otherwise, <c>false</c>.
        /// </value>
        public bool IsMultiLine
        {
            get { return _isMultiLine; }
            set { _isMultiLine = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                #region Register JS Script, if Not registered
                if (!Page.ClientScript. IsClientScriptIncludeRegistered("jQueryJsfilename"))
                {
                    string jQueryJsfilename = "UserPickerCSS_JS/Scripts/jquery-1.4.2.min.js";
                    Page.ClientScript .RegisterClientScriptInclude("jQueryJsfilename", jQueryJsfilename);
                }
                if (!Page.ClientScript. IsClientScriptIncludeRegistered("JQueryCore"))
                {
                    string jQueryAutoCompletefilename = "UserPickerCSS_JS/Scripts/jquery.ui.core.js";
                    Page.ClientScript .RegisterClientScriptInclude("JQueryCore", jQueryAutoCompletefilename);
                }
                if (!Page.ClientScript. IsClientScriptIncludeRegistered("JQueryUIWidget"))
                {
                    string jQueryAutoCompletefilename = "UserPickerCSS_JS/Scripts/jquery.ui.widget.js";
                    Page.ClientScript .RegisterClientScriptInclude("JQueryUIWidget", jQueryAutoCompletefilename);
                }
                if (!Page.ClientScript. IsClientScriptIncludeRegistered("JQueryPosition"))
                {
                    string jQueryAutoCompletefilename = "UserPickerCSS_JS/Scripts/jquery.ui.position.js";
                    Page.ClientScript .RegisterClientScriptInclude("JQueryPosition", jQueryAutoCompletefilename);
                }
                if (!Page.ClientScript. IsClientScriptIncludeRegistered("jQueryAutoCompletefilename"))
                {
                    string jQueryAutoCompletefilename = "UserPickerCSS_JS/Scripts/jquery.ui.autocomplete.js";
                    Page.ClientScript .RegisterClientScriptInclude("jQueryAutoCompletefilename", jQueryAutoCompletefilename);
                }
                #endregion

                if (IsMultiLine)
                {
                    txtSearch.TextMode = TextBoxMode.MultiLine;
                }
            }
        }
    }
}

In above code, at code behind, we have exposed one property named “isMultiline”, which will decide that our Autocomplete User picker control is multiline supported or not.

Also, it is possibility that user picker will be used more than one and we must assure that the javascript file should not be added multiple time. So we are checking that file is added or not and if the javascript file is not added then we are registering that on client side.

File Name : AutoComplete.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AutoComplete.ascx.cs" Inherits="AutoComplete.AutoComplete" %>
<link href='<%=Request.ApplicationPath +"UserPickerCSS_JS/css/jquery.ui.all.css"%>' rel="stylesheet" type="text/css" />
<link href="UserPickerCSS_JS/css/demos.css" rel="stylesheet" type="text/css" />
<style type="text/css">
	.ui-autocomplete-loading { background: white url('UserPickerCSS_JS/css/indicator.gif') right center no-repeat; }
	.SearchWidth{width:90%;}
</style>
<script type="text/javascript">

 $(function() {
		function split(val) {
			return val.split(/,s*/);
		}
		function extractLast(term) {
			return split(term).pop();
		}

		$("#<%=txtSearch.ClientID%>").autocomplete({
			source: function(request, response) {
				$.getJSON("UsersList.ashx", {
					term: extractLast(request.term)
				}, response);
			},
			search: function() {
				// custom minLength
				var term = extractLast(this.value);
				if (term.length < 2) {
					return false;
				}
			},
			focus: function() {
				// prevent value inserted on focus
				return false;
			},
			select: function(event, ui) {
				var terms = split( this.value );
				// remove the current input
				terms.pop();
				// add the selected item
				terms.push( ui.item.value );
				// add placeholder to get the comma-and-space at the end
				terms.push("");
				this.value = terms.join(", ");
				return false;
			}
		});
	});

</script>
<asp:TextBox CssClass="SearchWidth" ID="txtSearch" runat="server" Rows="3"></asp:TextBox>
<asp:Image ImageAlign="top" ID="imgUsersWindow" ImageUrl="~/UserPickerCSS_JS/css/Users.PNG" ToolTip="Select a User(s)" style="cursor:pointer" runat="server" />

At client side, we have written some javascript code which is self explanatory.  In AJAX method we are calling handler “UsersList.ashx” which returns the JSON object.

Now, add this usercontrol anywhere in ASP.net page, it will just run with ultimate speed and UI.

Download Complete Working project of Ajax based Multiselect JQuery Autocomplete control in ASP.net. This attachment contains advanced control than explained in this article.  It has one UserPicker Window also where user can be selected in Bulk.

To control the height of the AutoComplete option displayed, add following css hack in your UserControl Page or where the Autocomplete is added in page:

<style type="text/css">
.ui-autocomplete {
max-height: 100px;
overflow-y: auto;
}
/* IE 6 doesn't support max-height
 * we use height instead, but this forces the menu to always be this tall
 */
* html .ui-autocomplete {
height: 100px;
}
</style>

Please share your comments and enhancement if needed.

Related posts

  • Shekhar

    thanks for this post about ajax & juery.

  • Aruna

    Hi Jitendra,

    I have downloaded the demo sample and changed the database connections.It is fetching the data while i am key in text box but those values are not displaying in the extender control.I only changed database connections and query.I am not able to figure out what is the problem.Please let me know what is the problem i am facing?My browser is IE 6.

    Appreciate your quick response,

    Aruna

    • http://shivasoft.in Jitendra Zaa

      Hi Aruna,

      I have not tested my application in IE 6, however i have few suggestions.

      Don’t fetch data from Database, instead try to create dummy list of emp and on line no 53 of “UsersList.ashx” serialize that, and check if it is running. “e.value” should be email id and “e.label” should be the name of the person. and if it does not work then try to add the “DOCTYPE” at the beginning of ASP.Net page.

      If this does not work then let me know.

      Thanks,
      Jitendra Zaa

  • http://www.csharpings.blogspot.com Jayant Bramhankar

    Nice Article,..
    Why don’t you use ScriptService, ScriptMethod? You will be then able set up better security about exposing Web Services.

    • http://shivasoft.in Jitendra Zaa

      Hi Jayant,
      Thanks for your comment. Here, i wanted to demonstrate the use of JQuery to call the ASP.Net handlers.
      There was no need of security and i wanted very light weight control. I have used Ajax manager provided by the ASP.Net, but it was very heavy and if i added 4-5 instances on same page then it was not responding.

      If you can provide me some good tutorial on ScriptService and ScriptMethod, then it will be much appreciated.

      Thanks,
      Jitendra Zaa

  • Sdfsfsd

    mj

    • Skaskaksjgdkjsagkjsjsala

       ok dea

  • Pingback: 10 Ajax/jQuery Autocomplete Tutorials/Plugins | jQuery4U | No.1 Resource for jQuery Developers

  • Pingback: 35+ Best Ajax jQuery Autocomplete Tutorial & Plugin with Examples « Yoyo142's Blog