Display AutoSuggest Textbox in Web API

Introduction

This articles describes the Auto Suggested TextBox in the Web API. Type a letter in the TextBox and press the Enter key. It then displays an Autosuggest list.

The following is the procedure for creating the application.

Step 1

Create a Web API application.

  • Start Visual Studio 2012.
  • From the start window Select "Installed" -> "Visual C#" -> "Web".
  • Select "ASP.NET MVC4 Web Application" and click on the "Ok" button.

    Select MVC4 Web Application

  • From the "MVC4 Project" window select "Web API".

    Select Web API

  • Click on the "OK" button.

Step 2

Now select the "HomeController".

  • In the "Solution Explorer".
  • Expand the Controller folder.
  • Select the "HomeController".
    Select Controller

Add the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8. namespace AutosuggestTextAPI.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         public ActionResult Index()  
  13.         {  
  14.             return View();  
  15.         }  
  16.         public DataTable Items()  
  17.         {  
  18.             DataTable cityname = new DataTable();  
  19.             cityname.Columns.Add("ID"typeof(int));  
  20.             cityname.Columns.Add("Level"typeof(string));  
  21.             cityname.Columns.Add("value"typeof(string));  
  22.             cityname.Columns.Add("word"typeof(string));  
  23.             DataRow dr = cityname.NewRow();  
  24.             dr["ID"] = 1;  
  25.             dr["Level"] = "2";  
  26.             dr["value"] = "Kanpur";  
  27.             dr["word"] = "KNP";  
  28.             cityname.Rows.Add(dr);  
  29.             dr = cityname.NewRow();  
  30.             dr["ID"] = 2;  
  31.             dr["Level"] = "3";  
  32.             dr["value"] = "Lucknow";  
  33.             dr["word"] = "LKW";  
  34.             cityname.Rows.Add(dr);  
  35.             dr = cityname.NewRow();  
  36.             dr["ID"] = 3;  
  37.             dr["Level"] = "4";  
  38.             dr["value"] = "Delhi";  
  39.             dr["word"] = "DLH";  
  40.             cityname.Rows.Add(dr);  
  41.             dr = cityname.NewRow();  
  42.             dr["ID"] = 3;  
  43.             dr["Level"] = "5";  
  44.             dr["value"] = "Banaras";  
  45.             dr["word"] = "BNA";  
  46.             cityname.Rows.Add(dr);  
  47.             dr = cityname.NewRow();  
  48.             dr["ID"] = 4;  
  49.             dr["Level"] = "6";  
  50.             dr["value"] = "Banglore";  
  51.             dr["word"] = "BNG";  
  52.             cityname.Rows.Add(dr);  
  53.             return cityname;  
  54.         }  
  55.         public ActionResult CityAutoSuggestByName(string autotext)  
  56.         {  
  57.             autotext = (autotext == null) ? "" : autotext;  
  58.             return Content(JsonForAutoSuggestforName(Items().Select("value  LIKE '%" + autotext + "%'")), "application/json");  
  59.         }  
  60.         static string loc;  
  61.         public static string JsonForAutoSuggestforName(DataRow[] datarow)  
  62.         {  
  63.             StringBuilder jsonBuilder = new StringBuilder();  
  64.             jsonBuilder.Append("[");  
  65.             for (int a = 0; a < datarow.Length; a++)  
  66.             {  
  67.                 jsonBuilder.Append("{\"ID\": \"");  
  68.                 jsonBuilder.Append(datarow[a][0].ToString());  
  69.                 jsonBuilder.Append("\",");  
  70.                 jsonBuilder.Append("\"Level\": \"");  
  71.                 loc = datarow[a][2].ToString().Replace("\\", "\\\\");  
  72.                 jsonBuilder.Append(loc.Replace("\"""\\\""));  
  73.                 jsonBuilder.Append("\",");  
  74.                 jsonBuilder.Append("\"value\": \"");  
  75.                 datarow[a][2].ToString().Replace("\\", "\\\\");  
  76.                 jsonBuilder.Append(loc.Replace("\"""\\\""));  
  77.                 jsonBuilder.Append("\",");  
  78.                 jsonBuilder.Append("\"word\": \"");  
  79.                 loc = datarow[a][3].ToString().Replace("\\", "\\\\");  
  80.                 jsonBuilder.Append(loc.Replace("\"""\\\""));  
  81.                 jsonBuilder.Append("\",");  
  82.                 jsonBuilder.Remove(jsonBuilder.Length - 1, 1);  
  83.                 jsonBuilder.Append("},");  
  84.             }  
  85.             jsonBuilder.Remove(jsonBuilder.Length - 1, 1);  
  86.             jsonBuilder.Append("]");  
  87.             string jason = jsonBuilder.ToString();  
  88.             return jsonBuilder.ToString();  
  89.         }  
  90.     }  
  91. }  

Step 3

Now write some HTML code in the "index.cshtml" file. This file exists:

  • In the "Solution Explorer".

  • Expand "Views" folder.

  • Select "Home" -> "index.cshtml".
    Select Index View

Add the following code:

  1. @{ ViewBag.Title = "Using AutoSuggest on Enter Key"; }  
  2. <table>  
  3.  <tr>  
  4.          <td style="width:320px">  
  5.                 @Html.TextBox("CityName"""new { @style = "width:320px;outline: 2px solid #FBEC88" })   
  6.          </td>  
  7.    </tr>  
  8. </table>  
  9. @section JavaScript {  
  10.     <script type="text/javascript">  
  11.         $(document).ready(function () {  
  12.             $("#CityName").autocomplete({  
  13.                 search: function (event, ui) {  
  14.                     var k = event.keyCode;  
  15.                     if (k == 13) {  
  16.                         return true;  
  17.                     }  
  18.                     else  
  19.                         return false;  
  20.                 },  
  21.                 source: function (request, response) {  
  22.                     $.ajax({  
  23.                         url: '@Url.Action("CityAutoSuggestByName")',  
  24.                         data: { autotextext: request.term },  
  25.                         dataType: 'json',  
  26.                         type: 'POST',  
  27.                         success: function (data) {  
  28.                             response(data);  
  29.                         }  
  30.                     });  
  31.                 },  
  32.                 select: function (event, ui) {  
  33.                     $('#CityName').val(ui.city ? ui.city.value : 'Select');  
  34.                 }  
  35.             });  
  36.         });  
  37.     </script>  
  38. }   

Step 4

Select the "_Layout.cshtml" file.

  • In the "Solution Explorer".

  • Expand "Views" folder.

  • Select "Shared" -> "_Layout.cshtml".
    Select Layout file

Add the following code:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>@ViewBag.Title</title>  
  5.     <link href="@Url.Content("~/Content/site.css")" rel="stylesheet" type="text/css" />  
  6.     <link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />    
  7. </head>  
  8. <body>  
  9.     <div class="page">  
  10.         <div id="header">  
  11.             <div id="title">  
  12.                 <h1>For AutoSuggested List Press Enter</h1>  
  13.             </div>  
  14.         </div>  
  15.         <div id="main">  
  16.             @RenderBody()  
  17.             <div id="footer">  
  18.             </div>  
  19.         </div>  
  20.     </div>  
  21.      <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>  
  22.        <script src="@Url.Content("~/Scripts/jquery-ui-1.8.7.min.js")" type="text/javascript"></script>  
  23.     @RenderSection("JavaScript"false)  
  24. </body>  
  25. </html>   

Step 5

Execute the application:

 Show Autosuggest List


Similar Articles