Using Ajax AutoCompleteExtender For Autosuggest



Ajax.jpg

Introduction

In the present scenario, we need our text boxes to act more user friendly and auto suggest is a feature that makes them more user friendly. Moreover the chance of making typographical mistakes are also reduced. This article will help you in adding a simple auto suggest feature using Ajax AutoCompleteExtender.

Background

A service is used to call the data from a database. This autosuggest will populate top ten records on the basis of the letter entered by you. For example, if we type "A", the top ten names beginning with the letter "A", then we make it "An", then top 10 beginning with "An".

Using the Code

Code is populating auto suggest for a company. What we need from the service is the name of the company and its ID. So here is the method that we are writing in the service to get the top 10 companies starting with the text typed by the user in the TextBox.

The name of the service is "CompanyServiceForAutoSuggest" in which exists the method GetCompanyList which includes two parameters:

  • "prefixText" the text to be searched to populate the autosuggest
  • "count" the maximum number of records in the auto suggest

The method returns an array string, which includes company name and its ID.

[WebMethod]
 
public String[] GetCompanyList(String prefixText, Int32 count)
        {
           
String[] strList = null;
            List<companymasterbo> objCompanyList =
new List<companymasterbo>();
            List<string> strCompanyList =
new List<string>();
           
short i;
            UtilityServiceClient lObjUtilityServiceClient =
null;
            CompanyMasterBO lObjCompanyMasterBO =
null;
            lObjCompanyMasterBO =
                
new ARGI.Vulcan.ServiceLayer.UtilityService.CompanyMasterBO();
            lObjCompanyMasterBO.Company = prefixText.Replace(
"'","''").ToString().Trim();
            lObjCompanyMasterBO.Count = count;         
           
try
            {
                lObjUtilityServiceClient =
new UtilityServiceClient();               
                objCompanyList = lObjUtilityServiceClient.GetCompanyList
                (lObjCompanyMasterBO);
// Method to get top 10 company from database
                 /* This is my query to get the records
                  @sql varchar(4000)                                       
                  set @sql = 'SELECT top ' + convert(varchar(10),@p_Count)  +
                                  ' comCompanyMasterID,comCompanyName 
                  from dbo.[CompanyMaster]  where comCompanyName LIKE
                          '''+@p_CompanyFirstName+'%'''      
                 exec (@sql) */
                if (objCompanyList.Count > 0)
                {
                   
for (i = 0; i < objCompanyList.Count; i++)
                    {
                        strCompanyList.Add(AjaxControlToolkit.
                          AutoCompleteExtender.CreateAutoCompleteItem
                        (objCompanyList[i].Company, Convert.ToString
                        (objCompanyList[i].CompanyMasterID.ToString())));
                    }
                    strList =
new String[10];
                    strList = strCompanyList.ToArray();
                }
               
else
                {
                   
//strList = new String[1];
                    //strList[0] = "No Match Found";
                }              
            }
           
catch (System.ServiceModel.FaultException FaultExp)
            {
               
throw;
            }
           
catch (Exception ex)
            {
               
throw;
            }
           
finally
            {
               
if (lObjUtilityServiceClient != null)
                    lObjUtilityServiceClient =
null;
               
if (lObjCompanyMasterBO != null)
                    lObjCompanyMasterBO =
null;
            }
           
return strList;
        }


I have created a control, as it needs to be placed at many locations. The name of my control is ucCompany.

On the ucCompany.ascx page, write the following lines:

<asp:TextBox ID="txtAutoCompleteforCompany" name="txtAutoCompleteforCompany" runat="server" onblur="showMessage()" autocomplete="off"></asp:TextBox>
<
ajaxtoolkit:TextBoxWatermarkExtender ID="txtAutoCompleteforCompany_waterMark" runat="server" TargetControlID="txtAutoCompleteforCompany"
        
WatermarkText="Add New Company..."Enabled="true">
</
ajaxtoolkit:TextBoxWatermarkExtender>
<
div id="listPlacement" class="cls_listPlacement"></div>
<
ajaxtoolkit:AutoCompleteExtender ID="txtAutoCompleteforCompany_AutoCompleteExtender"
         MinimumPrefixLength="1" TargetControlID="txtAutoCompleteforCompany"
        
CompletionSetCount="10"CompletionInterval="100"
        
ServiceMethod="GetCompanyList"
        
ServicePath="../UiHelper/CompanyServiceForAutoSuggest.asmx"
         runat="server" OnClientItemSelected="setCompanyMasterID"
        
CompletionListElementID="listPlacement">
</
ajaxtoolkit:AutoCompleteExtender>
<
input type="hidden" id="hdnCompanyMasterId"
        
name="hdnCompanyMasterId" runat="server" value="0" />
<
input type="hidden" id="hdnCompanyName"
        
name="hdnCompanyName" runat="server" value="" />


ServicePath is the actual path where my service is saved. So my service will be called here. TargetControlIDis the name of the control on which auto suggest will display its result. OnClientItemSelected we are calling a JS function named "SetCompanyMasterID", by using this method, I am setting the ID and Name in a hidden variable, to use them as and when required.

Add the script tag in ucCompany.ascx and define the js function:

<script type="text/javascript">
function setCompanyMasterID(source, eventargs)
 {
      document.getElementById (
"hdnCompanyMasterId.ClientID").value =
                                                    eventargs.get_value();
      document.getElementById (
"hdnCompanyName.ClientID").value =
         document.getElementById (
"txtAutoCompleteforCompany.ClientID").value;
 }
</script>

On the ucCompany.ascx.cs file, we are creating two methods:

  • "GetCompanyMasterId" to fetch the Company ID
  • "GetCompanyName" to get the name of the company

public int GetCompanyMasterId()
        {
           
try
            {
               
if (hdnCompanyMasterId.Value.Trim() != String.Empty &&
                          hdnCompanyMasterId.Value.Trim() !=
"0")
                {
                   
if (hdnCompanyName.Value.Trim() ==
                                   txtAutoCompleteforCompany.Text.Trim())
                    {
                       
return Convert.ToInt32(hdnCompanyMasterId.Value);
                    }
                   
else
                    {
                       
return 0;
                    }
                }
               
else
                {
                   
return 0;
                }
            }
           
catch
            {
               
throw;
            }
           
finally
            {
 
            }
        }
 
public string GetCompanyName()
        {
           
try
            {
               
if (txtAutoCompleteforCompany.Text.Trim() != String.Empty)
                {
                   
return txtAutoCompleteforCompany.Text.Trim();
                }
               
else
                {
                   
return string.Empty;
                }
            }
           
catch
            {
               
throw;
            }
           
finally
            {
            }
        }

My control was placed inside another control. So I lost the value of ID and Name after the post back. So I wrote my JS method on server side and if the page load occurs, I call my JS method forcefully. In case you are using this control directly, then this step won't be required.

protected void Page_Load(object sender, EventArgs e)
 {
     RegisterClientScript();      
 }
 
public void RegisterClientScript()
 {
     StringBuilder cstext2 =
new StringBuilder();
     cstext2.Append(
"<script type=\"text/javascript\">
        function setCompanyMasterID(source, eventargs) {"
);
     cstext2.Append(
"document.getElementById ('" + ClientID +
        
"_hdnCompanyMasterId').value = eventargs.get_value();");
     cstext2.Append(
"document.getElementById ('" + ClientID +
        
"_hdnCompanyName').value = document.getElementById
         ('"
+ ClientID + "_txtAutoCompleteforCompany').value; }");
     cstext2.Append(
" </script>");          
         ScriptManager.RegisterClientScriptBlock(
this, GetType(),
        
"OnClientItemSelected", cstext2.ToString(),false);
 }


Finally calling the control on a page, on the .cs file of the page, you can use:

// UcCompany is the ID of the control
string Company = UcCompany.GetCompanyName();        // To get the compnay name selected
   int CompanyMasterID = UcCompany.GetCompanyMasterId();// To get the ID of
                                            // the company selected using auto suggest
Points of Interest

So far, I have used various Auto suggest using JavaScript and JQuery, this was the first time I was asked by my client that he needs Ajax control only. So I have implemented and found it interesting too. Hope it helps you too to add Auto suggest feature using AJAX.

Up Next
    Ebook Download
    View all
    Learn
    View all