Click here to Skip to main content
12,752,054 members (32,359 online)
Click here to Skip to main content
Add your own
alternative version


15 bookmarked
Posted 9 Jan 2014

AutoCompleteExtender with WCF using Entity Framework

, 9 Jan 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
AutoCompleteExtender with WCF

AutoCompleteExtender is an extender available in AjaxControlToolkit which can be attached to any TextBox control.When user enters a characters in TextBox which is extended by AutoCompleteExtender, AutoCompleteExtender pulls out the words that starts with the contents of the TextBox from database or specified memory location and display them in popup list. It enables ASP.NET TextBox control to behave like a search box.


In general ASP.NET Webservices are used with AutoCompleteExtender to display the results. WCF provides rich support to build services for Ajax and Silverlight clients with different attributes and different hosting classses. It is easy to build this kind of services, because we have Ajax enabled WCF service template which is provided in Visual Studio 2010 and above, automates the entire process of developing WCF services. Performance wise WCF services are faster than Webservices and we can use light weight message exchange format like JSON with WCF services. So the WCF services can be used with AutoCompleteExtender to produce quick and efficient results.

Using the code  

  1. Create table Names to store Id(int type primary key) and Name(varchar type) in SQL Server database using SQL Server Mangement Studio

  2. Create New website Project
     Goto File -> New -> Website -> Select Visual C# under Templates
    -> Select ASP.NET Empty Website template -> Click OK 

  3. Adding Entity Data Model.
    • Goto Solution Explorer -> Right click on Website -> Goto Add -> Goto Add New Item -> Select ADO.NET Entity Data Model -> Click on OK 
    • In Entity Data Model Wizard.
      Select Generate from databse option -> Click on Next -> Click on New Connection -> Provide required fields in Connection Settings window -> Click on OK -> Select 'Yes, include the sensitive data in the connection string.' radiobutton -> Check 'Save entity connection string in Web.config as' checkbox and write MYDBEntities in following textbox -> Click on Next -> Click on Tables -> Add Names table -> Give Model Namespace name as <code><code>MYDBEntities -> Click on Finish -> Build the project.  
    • Result :- This process will generate Model.context.cs and Model.cs class in App_Code folder.
      Context class :- Enables us to perform CRUD operations on table using DbSet class.

      Model class
       :- Contains Names entity from database which is converted into class.

    -Sometimes Model.context.cs and Model.cs classes will not create. In such case follow the following troubleshoot procedure
         Right click on and -> Run Custom tool

    This will generate Model.context.cs and Model.cs class in App_Code folder.

    -Check for ConnectionString in web.config file. If it is not added then addconnectionString in Configuration tag as follows
     <add name="MYDBEntities" connectionString="metadata=res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=MYDB;user id=sa;password=123;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

  4. Preparing Ajax enabled WCF service.

    • Goto Solution Explorer -> Right click on website -> Goto Add -> Goto Add New Template -> Select Ajax Enabled WCF Service Template -> Click on OK.

      Result :-
      -A regular Service.svc file added to App_Code.

      -No interface only class Service.cs. ServiceContract is written directly for class.

      -In web.config webHttpBinding endpoint along with enableWebScript behavior
    • In Service.cs file write OperationContract as required. In this example class Service written as follows.

      [ServiceContract(Namespace = "")]
      [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
      public class Service
         //Specifying message exchange format is JSON 
          public List<string> GetNames(string prefixText)
              MYDBEntities obj=new MYDBEntities ();
              var x = from n in obj.names
                      select n;
              List<string> name = new List<string> ();
              foreach (var item in x)
              return name;

      -Specify ResponseFormat parameter of WebInvoke attribute as WebMessageFormat.JSON to specify the message exchange format as JSON.

      -Method name GetNames can be replaced with name of your choice, but the return type and parameter name and type must exactly match including case.

      -GetNames method is value returning method, it returns list of names from Names table which matched with characters contains in prefixText parameter.

    Note :-
    The above service can not be tested as it requires metadata. To test this service add an endpoint with mexHttpBinding. 

  5. Assuming that AjaxControlToolKit.dll is already added to the project and registered in web.config file as following in system.web tag
  6. <pages>
    <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit"/>

  7. Add one appSettings tag in Configuration tag  as follows to set UnobtrusiveValidatonMode to false
  8. <appSettings>
        <add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>

  9. Add ASP.NET empty website template to the website project and name it as Deafault.aspx. In source view of Default.aspx write the following code.
    • In head tag add comletionList, item anditemHighLight css classes in style tag 
      .completionList {
                  border:2px solid lightskyblue;
      .item { 
                  height: 17px; 

      The above css classes is added to use with CompletionListCssClass CompletionListItemCssClass and CompletionListHighlightedItemCssClass property of AutoCompleteExtender . It will apply on popup list while displaying the search result.

    • Now in form tag of Default.aspx page. Add one TextBox with AutoCompleteExtender as follows
        1  <form id="form1" runat="server">
        2   <ajaxToolkit:ToolkitScriptManager runat="server"></ajaxToolkit:ToolkitScriptManager>
        3      <div>
        4      <b>Enter Name:</b>&nbsp;<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        5      <ajaxToolkit:AutoCompleteExtender ID="ace1" TargetControlID="txtName" runat="server" ServiceMethod="GetNames" ServicePath="Service.svc" EnableCaching="true" MinimumPrefixLength="1" CompletionListCssClass="completionList" CompletionListItemCssClass="item" CompletionListHighlightedItemCssClass="itemHighLight"></ajaxToolkit:AutoCompleteExtender>
        6      </div> 
        7  </form> 
    AutoCompleteExtender properties which are used in this example are as follows:-

    TargetControlID The TextBox control where the user types content should be automatically populated.
    ServiceMethodThe WCF service method to be called.
    ServicePath The path to the WCF service that the extender uses to produce the result.
    MinimumPrefixLengthMinimum number of characters that must be entered before getting suggestions from the WCF service.
    CompletionIntervalTime in milliseconds. After each interval AutoCompleteExtender get suggestions from WCF webservice.
    EnableCaching Specifies client side caching is enabled or not
    CompletionListCssClassCss class that will be used to style the completion list layout.
    CompletionListItemCssClassCss class that will be used to style an item in autocomplete list.
    CompletionListHighlightedItemCssClassCss class that will be used to style a highlighted item in the completion list.

  10. Run the website to check the following output 


Points of Interest

  • Using Ajax Enabled WCF service to test the AutoCompleteExtender. 
  • Using Entity Framework  to get the records from database. 


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


About the Author

Vinay Jade
Student NA
India India
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy vote of 5 Pin
Member 1206331415-Oct-15 23:55
memberMember 1206331415-Oct-15 23:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170217.1 | Last Updated 10 Jan 2014
Article Copyright 2014 by Vinay Jade
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid