Auto Suggest Search Items in C# using jQuery, Ajax and JSON

This article will focus on the auto suggest searching that we see mainly in product listing websites or in simple word searches in ecommerce.

Prerequisites

Basic knowledge of,

  • JQuery
  • Ajax
  • Json

JS

  1. <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>  
  2.   
  3. <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>  
CSS
  1. <link rel="stylesheet"href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  
Assume that you have a running project with a web form in which there is a search textbox with button. Let's take the following image for your better understanding.

Search

UI
  1. <div role="search" method="get" class="search-form">   
  2.    <input type="search" class="search-field" placeholder="So, What are you looking for" value="" id="searchresult" title="Search">   
  3.    <input type="submit" class="search-submit" value="">   
  4. </div>  
run

On every key stroke there is a function call and according to that input text auto suggestions are available.
  1. $('#searchresult').keyup(function(event)  
  2. {  
  3.     ptxt = $('#searchresult').val();  
  4.     $('#searchresult').autocomplete(  
  5.     {  
  6.         scroll: true,  
  7.         selectFirst: false,  
  8.         autoFocus: false,  
  9.         source: function(request, response)  
  10.         {  
  11.             $.ajax(  
  12.             {  
  13.                 type: "POST",  
  14.                 contentType: "application/json; charset=utf-8",  
  15.                 url: "../login.asmx/searchresult",  
  16.                 data: "{'prefixtext':'" + ptxt + "'}",  
  17.                 dataType: "json",  
  18.                 success: function(data)  
  19.                 {  
  20.                     response($.map(data.d, function(item)  
  21.                     {  
  22.                         return {  
  23.                             label: item.split('/')[0],  
  24.                             val: item.split('/')[1]  
  25.                         }  
  26.                     }));  
  27.                 },  
  28.                 error: function(result) {}  
  29.             });  
  30.         },  
  31.         minLength: 2,  
  32.         select: function(event, ui)  
  33.         {  
  34.             var vll = ui.item.val;  
  35.             var sts = "no";  
  36.             var url = 'Productlist.aspx?prefix=' + ptxt; // ur own conditions  
  37.             $(location).attr('href', url);  
  38.         }  
  39.     });  
  40.     if(event.keyCode == 13)  
  41.     { // this event fired when enter is pressed  
  42.         url = 'Productlist.aspx?prefix=' + ptxt; // ur own conditions  
  43.         $(location).attr('href', url);  
  44.         return false;  
  45.     }  
  46. });  
  47. $('#sch').click(function()  
  48. //  this event fired on button click  
  49.    ptxt = $('#searchresult').val();  
  50.    url = 'Productlist.aspx?prefix=' + ptxt; // ur own conditions  
  51.    $(location).attr('href', url);  
  52. });  
  53. });  
The above code covers all the conditions for searching; wether searching a specific item, searching on button click, or searching corresponds to a specific keyword.

login.asmx/searchresult Page - Function is used for auto suggest searching; on every key stroke this function is called and shows you the result.
  1. [WebMethod(EnableSession = true)]  
  2. public List < string > searchresult(string prefixtext)  
  3. {  
  4.     List < string > result = new List < string > ();  
  5.     SqlConnection con = null;  
  6.     con = (SqlConnection) HttpContext.Current.Session["conn"];  
  7.     using(SqlCommand cmd = new SqlCommand("select pa.product_id,product_code,product_name,pa.category_id,pa.subcategory_id, where pa.avail_start<=GETDATE() and pa.avail_end>=GETDATE() and (product_code like '%" + prefixtext + "%' or product_name like '%" + prefixtext + "%' or category_name like '%" + prefixtext + "%' or subcategory_name like '%" + prefixtext + "%')", con))  
  8.     {  
  9.         con.Open();  
  10.         SqlDataReader dr = cmd.ExecuteReader();  
  11.         while(dr.Read())  
  12.         {  
  13.             result.Add(string.Format("{0}/{1}", dr["product_name"], dr["product_id"]));  
  14.         }  
  15.         con.Close();  
  16.         return result;  
  17.     }  
  18. }  
After this, the page is redirected to the listing page that shows the product list according to your search keyword. On this page load it passes this keyword to your query.

This my first article and I tried to cover all the cases for a search, and I persnally used this searching criteria  for e-commerce applications. If anybody has any query don't hesitate to ask, just ask your query in the comments.