MVC4: jQuery AutoComplete TextBox Using Web API

The following is my Data Table from which I will show the records.


Image 1

Open Visual Studio and go to "File" -> "New" -> "Project..." and you will get the New Project window as in the following:


Image 2


Image 3


We will now add our Data Table. So right-click on the Models folder then select "Add" -> "ADO.NET Entity Data Model".


Image 4

Give it a name.


Image 5


Image 6


Image 7


Image 8



Image 9


Image 10


Now it is time to add the Web API. So Right-click on Controller -> Add -> Controller.


Image 11

Select API Controller with read/write actions, using Entity Framework from the Template, select Model Class and select Data Context Class then click Add.


Image 12

This StudentAPI controller will generate code for Get, Put, Post & Delete methods. Here I modify my Get method since I need to pass my search text.

Here we need only a Get method.

The following is my StudentAPIController class:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Web;  
  10. using System.Web.Http;  
  11. using jQuery_AutoComplete_WithWEBAPI.Models;  
  12.   
  13. namespace jQuery_AutoComplete_WithWEBAPI.Controllers  
  14. {  
  15.     public class StudentAPIController : ApiController  
  16.     {  
  17.         private SchoolManagementEntities db = new SchoolManagementEntities();  
  18.   
  19.         // GET api/Student  
  20.         public IEnumerable<Student> GetStudents(string searchText)  
  21.         {  
  22.             return db.Student.Where(m => m.Name.Contains(searchText)).ToList();  
  23.         }  
  24.   
  25.         // GET api/StudentAPI/5  
  26.         public Student GetStudent(int id)  
  27.         {  
  28.             Student student = db.Student.Find(id);  
  29.             if (student == null)  
  30.             {  
  31.                 throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));  
  32.             }  
  33.   
  34.             return student;  
  35.         }  
  36.   
  37.         // PUT api/StudentAPI/5  
  38.         public HttpResponseMessage PutStudent(int id, Student student)  
  39.         {  
  40.             if (ModelState.IsValid && id == student.StudentID)  
  41.             {  
  42.                 db.Entry(student).State = EntityState.Modified;  
  43.   
  44.                 try  
  45.                 {  
  46.                     db.SaveChanges();  
  47.                 }  
  48.                 catch (DbUpdateConcurrencyException)  
  49.                 {  
  50.                     return Request.CreateResponse(HttpStatusCode.NotFound);  
  51.                 }  
  52.   
  53.                 return Request.CreateResponse(HttpStatusCode.OK);  
  54.             }  
  55.             else  
  56.             {  
  57.                 return Request.CreateResponse(HttpStatusCode.BadRequest);  
  58.             }  
  59.         }  
  60.   
  61.         // POST api/StudentAPI  
  62.         public HttpResponseMessage PostStudent(Student student)  
  63.         {  
  64.             if (ModelState.IsValid)  
  65.             {  
  66.                 db.Student.Add(student);  
  67.                 db.SaveChanges();  
  68.   
  69.                 HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, student);  
  70.                 response.Headers.Location = new Uri(Url.Link("DefaultApi"new { id = student.StudentID }));  
  71.                 return response;  
  72.             }  
  73.             else  
  74.             {  
  75.                 return Request.CreateResponse(HttpStatusCode.BadRequest);  
  76.             }  
  77.         }  
  78.   
  79.         // DELETE api/StudentAPI/5  
  80.         public HttpResponseMessage DeleteStudent(int id)  
  81.         {  
  82.             Student student = db.Student.Find(id);  
  83.             if (student == null)  
  84.             {  
  85.                 return Request.CreateResponse(HttpStatusCode.NotFound);  
  86.             }  
  87.   
  88.             db.Student.Remove(student);  
  89.   
  90.             try  
  91.             {  
  92.                 db.SaveChanges();  
  93.             }  
  94.             catch (DbUpdateConcurrencyException)  
  95.             {  
  96.                 return Request.CreateResponse(HttpStatusCode.NotFound);  
  97.             }  
  98.   
  99.             return Request.CreateResponse(HttpStatusCode.OK, student);  
  100.         }  
  101.   
  102.         protected override void Dispose(bool disposing)  
  103.         {  
  104.             db.Dispose();  
  105.             base.Dispose(disposing);  
  106.         }  
  107.     }  

Now add a controller. Right-click on the Controller folder then select Add -> Controller.


Image 13

Now add a View. So right-click on the Index Method then select Add View.


Image 14


Image 15


Make sure your solution has the following JavaScript and CSS files. Otherwise you can download these from the jQuery site.

jquery-1.8.2.js
jquery-ui-1.9.0.js
& jquery-ui-1.9.0.custom.css


Now our Index.cshtml is:

  1. @{  
  2.     ViewBag.Title = "jQuery AutoComplete Text Box using WEB API";  
  3.       
  4. }  
  5.   
  6. <link href="~/CSS/jquery-ui-1.9.0.custom.css" rel="stylesheet" />  
  7. <script src="~/Scripts/jquery-1.8.2.js"></script>  
  8. <script src="~/Scripts/jquery-ui-1.9.0.min.js"></script>  
  9. <style>  
  10.     .ui-autocomplete {  
  11.         max-height: 100px;  
  12.         overflow-y: auto;  
  13.     }  
  14.   
  15.     .ui-autocomplete {  
  16.         height: 100px;  
  17.     }  
  18. </style>  
  19. <div id="body">  
  20.     <table style="background-color: skyblue; border: solid 4px green; width: 80%; text-align: center;">  
  21.         <tr>  
  22.             <td>  
  23.                 <label for="autocomplete-textbox">Enter User Name : </label>  
  24.             </td>  
  25.             <td style="text-align: left">  
  26.                 <input type="text" id="txtName" /></td>  
  27.         </tr>  
  28.         <tr>  
  29.             <td></td>  
  30.         </tr>  
  31.         <tr>  
  32.             <td>  
  33.                 <label id="lblMessage" style="color: red;"></label>  
  34.             </td>  
  35.             <td style="text-align: left">  
  36.                 <label id="lblSelectedVal" style="color: magenta;"></label>  
  37.             </td>  
  38.         </tr>  
  39.     </table>  
  40. </div>  
  41.   
  42. <script type="text/javascript">  
  43.     $(document).ready(function () {  
  44.         $('#txtName').autocomplete({  
  45.             source: function (request, response) {  
  46.                 var autocompleteUrl = '/api/StudentAPI' + '?searchText=' + request.term;  
  47.                 $.ajax({  
  48.                     url: autocompleteUrl,  
  49.                     type: 'GET',  
  50.                     cache: false,  
  51.                     dataType: 'json',  
  52.                     success: function (json) {  
  53.                         response($.map(json, function (data, id) {  
  54.                             return {  
  55.                                 label: data.Name,  
  56.                                 value: data.Name  
  57.                             };  
  58.                         }));  
  59.                     },  
  60.                     error: function (xmlHttpRequest, textStatus, errorThrown) {  
  61.                         console.log('some error occured', textStatus, errorThrown);  
  62.                     }  
  63.                 });  
  64.             },  
  65.             minLength: 1,  
  66.             select: function (event, ui) {  
  67.                 lblMessage.innerText = "Your Selected Name :";  
  68.                 lblSelectedVal.innerText = ui.item.label;  
  69.                 $('#txtName').val(ui.item.label);  
  70.                 return false;  
  71.             }  
  72.         });  
  73.     });  
  74. </script> 

Run the application.


Image 16


Image 17


Image 18


Image 19