Creating Autocomplete Using JQuery, Ajax & WCF in ASP.Net

Create an ASP.NET application.

Add a folder named Service to the project.

Add a WCF Service in the Service folder as in the following:

wcf service

You will see that two files are create, one has a .svc extension and the other is the interface class.

Open Iservice1.cs interface.

Add a method to get the Customer Name as in the following.

If Webinvoke is not found then add the reference from .Net as in the following:

  1. namespace AutoComplete_WCF_Jquery_AJAX_Call.Service {    
  2.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.    
  3.     [ServiceContract]    
  4.     public interface IService1 {    
  5.         [OperationContract]    
  6.         [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]    
  7.         string GetCustomers(string AutoData);    
  8.     }    

Add Method

Add a method under the .Svc class like below. We must define a connection string in webconfig or you can define one in this class also:

  1. namespace TestAppwith_Jquery.Services {    
  2.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.    
  3.     
  4.     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]    
  5.     public class Service: IService {    
  6.         public string GetCustomers(string prefix) {    
  7.             List < object > customers = new List < object > ();    
  8.             using(SqlConnection conn = new SqlConnection()) {    
  9.                 conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;    
  10.                 using(SqlCommand cmd = new SqlCommand()) {    
  11.                     cmd.CommandText = "SELECT * FROM dbo.studentmaster where " +    
  12.                         "StdName like @prefix + '%'";    
  13.                     cmd.Parameters.AddWithValue("@prefix", prefix);    
  14.                     cmd.Connection = conn;    
  15.                     conn.Open();    
  16.                     using(SqlDataReader sdr = cmd.ExecuteReader()) {    
  17.                         while (sdr.Read()) {    
  18.                             customers.Add(new {    
  19.                                 Id = sdr["AdmNo"],    
  20.                                 Name = sdr["StdName"]    
  21.                             });    
  22.                         }    
  23.                     }    
  24.                     conn.Close();    
  25.                 }    
  26.                 return (new JavaScriptSerializer().Serialize(customers));    
  27.             }    
  28.         }    
  29.     }    

To call WCF Service in aspx page add the following code:

  1. <html    
  2.     xmlns="http://www.w3.org/1999/xhtml">    
  3.     <head id="Head1" runat="server">    
  4.         <title></title>    
  5.         <style>    
  6.             table, th , td {    
  7.                 border: 1px solid grey;    
  8.                 border-collapse: collapse;    
  9.                 padding: 5px;    
  10.             }    
  11.             table tr:nth-child(odd) {    
  12.                 background-color: #f1f1f1;    
  13.             }    
  14.             table tr:nth-child(even) {    
  15.                 background-color: #ffffff;    
  16.             }    
  17.         </style>    
  18.         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>    
  19.         <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>    
  20.         <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>    
  21.         <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>    
  22.         <script type = "text/javascript">    
  23.         $(document).ready(function () {    
  24.             $("#search12").click(function () {    
  25.                 $.ajax({    
  26.     
  27.                     type: "POST",    
  28.                     contentType: "application/json; charset=utf-8",    
  29.                     url: "../Service/Service1.svc/GetCustomers",    
  30.                     data: '{"AutoData": "' + $("#AutoData").val() + '"}',    
  31.                     processData: false,    
  32.                     dataType: "json",    
  33.                     success: function (response) {    
  34.                         var customers = eval(response.d);    
  35.                         var html = "";    
  36.                         html += "    
  37.                         <table >    
  38.                             <tr>    
  39.                               <td>ID</td>    
  40.                               <td>Name</td>    
  41.                             </tr>";    
  42.                             $.each(customers, function () {    
  43.                                 html += "    
  44.                                 <tr>    
  45.                                     <td>" + this.Id + "</td>    
  46.                                     <td>" + this.Name + "</td>    
  47.                                 </tr>";    
  48.                             });    
  49.                             html += "    
  50.                          </table>";    
  51.                         $("#results").html(html == "" ? "No results" : html);    
  52.                     },    
  53.                     error: function (a, b, c) {    
  54.                         alert(a.responseText);    
  55.                     }    
  56.                 });    
  57.             });    
  58.         });    
  59.     
  60.         </script>    
  61.     </head>    
  62.     <body>    
  63.         <form id="form1" runat="server">    
  64.             <input type = "text" id = "AutoData" />    
  65.             <input id = "search12" type = "button" value = "Search" />    
  66.             <div id = "results"></div>    
  67.         </form>    
  68.     </body>    
  69. </html> 

Change in the web config as in the following code to add your Service Name and contract Name:

  1. <system.serviceModel>    
  2.     <behaviors>    
  3.         <serviceBehaviors>    
  4.             <behavior name="ServiceBehavior">    
  5.                 <serviceMetadata httpGetEnabled="true"/>    
  6.                 <serviceDebug includeExceptionDetailInFaults="true"/>    
  7.             </behavior>    
  8.         </serviceBehaviors>    
  9.         <endpointBehaviors>    
  10.             <behavior name="ServiceAspNetAjaxBehavior">    
  11.                 <enableWebScript/>    
  12.             </behavior>    
  13.         </endpointBehaviors>    
  14.     </behaviors>    
  15.     <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>    
  16.     <services>    
  17.         <service behaviorConfiguration="ServiceBehavior" name="AutoComplete_WCF_Jquery_AJAX_Call.Service.Service1">    
  18.             <endpoint address="" binding="webHttpBinding" contract="AutoComplete_WCF_Jquery_AJAX_Call.Service.IService1" behaviorConfiguration="ServiceAspNetAjaxBehavior">    
  19.                 <identity>    
  20.                     <dns value="localhost"/>    
  21.                 </identity>    
  22.             </endpoint>    
  23.             <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>    
  24.         </service>    
  25.     </services>    
  26. </system.serviceModel> 

The output will be like the following:

list