Click here to Skip to main content
15,886,067 members
Articles / Web Development / ASP.NET

AutoCompleteExtender with WCF using Entity Framework

Rate me:
Please Sign up or sign in to vote.
4.80/5 (5 votes)
9 Jan 2014CPOL4 min read 41.4K   275   15   1
AutoCompleteExtender with WCF
Introduction 

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.

Goal  

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.
    Note:-

    -Sometimes Model.context.cs and Model.cs classes will not create. In such case follow the following troubleshoot procedure
         Right click on Model.context.tt and Model.tt -> 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 add connectionString in Configuration tag as follows
    XML
    <connectionStrings>
     <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" />
    </connectionStrings>

  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.

      C#
      [ServiceContract(Namespace = "")]
      [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
      public class Service
      {
          [OperationContract]                                                            
         //Specifying message exchange format is JSON 
          [WebInvoke(ResponseFormat=WebMessageFormat.Json)] 
          public List<string> GetNames(string prefixText)
          {
              MYDBEntities obj=new MYDBEntities ();
              var x = from n in obj.names
                      where n.name.Substring(0,prefixText.Length).ToLower()==prefixText.ToLower()
                      select n;
              List<string> name = new List<string> ();
              foreach (var item in x)
              {
                  name.Add(item.name.ToString());
              }
              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. HTML
    <pages>
       <controls>
    <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit"/>
       </controls>
    </pages> 


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

  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 and itemHighLight css classes in style tag 
      HTML
      .completionList {
                  padding:0px;
                  margin:0px;
                  color:black;
                  overflow:auto;
                  text-align:left;
                  border:2px solid lightskyblue;
                  list-style-type:none;
                  cursor:default;
                  height:200px;
              }                                                                     
      .item { 
                  height: 17px; 
                  cursor:pointer; 
            }
              
      .itemHighLight{   
                  color:White; 
                  background-color:lightskyblue;
                  cursor:pointer; 
                    }

      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
      ASP.NET
        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:-

    PropertiesDescription
    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.
    EnableCachingSpecifies 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 

Image 1
 

Points of Interest

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

License

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


Written By
Student NA
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1206331415-Oct-15 22:55
Member 1206331415-Oct-15 22: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.