AutoComplete Textbox in MVC Using jQuery and WebAPI

This article explains how to use the TextBox AutoComplete feature in MVC 4 using the Web API and jQuery.

Getting Started

Use the following procedure to get started:

  • Create a new project in Visual Studio 2012
  • Select the "Web" tab and "ASP.NET MVC 4 Web Application"
  • Supply the project name and the Save location and click "Ok" button
  • Now select Web API project template and Razor view engine
  • Check "Unit test project" if you want to create a unit test project
  • Click the "OK" button

New Project in Visual Studio 2012

Image 1.

This is my Portal database script.

  1. USE [Portal]  
  2. GO  
  3. /****** Object:  Table [dbo].[Portal_Contacts]    Script Date: 11/14/2013 09:13:44 ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE TABLE [dbo].[Portal_Contacts](  
  9.             [ItemID] [int] IDENTITY(0,1) NOT NULL,  
  10.             [ModuleID] [intNOT NULL,  
  11.             [CreatedByUser] [nvarchar](100) NULL,  
  12.             [CreatedDate] [datetime] NULL,  
  13.             [Name] [nvarchar](50) NULL,  
  14.             [Role] [nvarchar](100) NULL,  
  15.             [Email] [nvarchar](100) NULL,  
  16.             [Contact1] [nvarchar](250) NULL,  
  17.             [Contact2] [nvarchar](250) NULL,  
  18.  CONSTRAINT [PK_Contacts] PRIMARY KEY NONCLUSTERED  
  19. (  
  20.             [ItemID] ASC  
  21. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  22. ON [PRIMARY]  
  23. GO 

Now add a connection string in the web.config fle as in the following:

  1. <connectionStrings>  
  2.     <add name="PortalConnectionString" connectionString="Data Source=.;Initial Catalog=Portal;Integrated Security=True" providerName="System.Data.SqlClient" />  
  3. </connectionStrings>

Now add model classes as in the following:

  1. public class PortalContacts  
  2. {  
  3.     public int ItemId { getset; }  
  4.     // public string Name { get; set; }  
  5.     public string Role { getset; }  
  6.     //public string Email { get; set; }  
  7.     //public string Contact1 { get; set; }  
  8.     //public string Contact2 { get; set; }  
  9. } 

The following is my repository class:

  1. public class PortalContactsRepository  
  2. {  
  3.     public IEnumerable<PortalContacts> GetContacts()  
  4.     {  
  5.         using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["PortalConnectionString"].ConnectionString))  
  6.         {  
  7.             connection.Open();  
  8.             using (SqlCommand command = new SqlCommand(@"SELECT [ItemID]       
  9.       ,[Name]  
  10.       ,[Role]  
  11.       ,[Email]  
  12.       ,[Contact1]  
  13.       ,[Contact2]  
  14.   FROM [Portal].[dbo].[Portal_Contacts]", connection))  
  15.   {  
  16.        // Make sure the command object does not already have  
  17.        // a notification object associated with it.  
  18.        command.Notification = null;  
  19.        if (connection.State == ConnectionState.Closed)  
  20.           connection.Open();  
  21.           using (var reader = command.ExecuteReader())  
  22.           return reader.Cast<IDataRecord>()  
  23.           .Select(x => new PortalContacts()  
  24.            {  
  25.                   ItemId = x.GetInt32(0),  
  26.                   // Name = x.GetString(1),  
  27.                   Role = x.GetString(2),  
  28.                   //Email = x.GetString(3),  
  29.                   //Contact1 = x.GetString(4),  
  30.                   //Contact2 = x.GetString(5)  
  31.               }).ToList();  
  32.             }  
  33.         }  
  34.     }  
  35. } 

Call the repository in the controller as in the following:

  1. using MvcApplication2.Models;  
  2. public class ValuesController : ApiController  
  3. {  
  4.     PortalContactsRepository objContacts = new PortalContactsRepository();  
  5.     // GET api/values  
  6.     public IEnumerable<PortalContacts> Get()  
  7.     {  
  8.         List<PortalContacts> plist = new List<PortalContacts>();  
  9.         plist = objContacts.GetContacts().ToList();  
  10.         return plist;  
  11.     }  
  12.     // GET api/values/5  
  13.     public string Get(int id)  
  14.     {  
  15.         return "value";  
  16.     }  
  17.     // POST api/values  
  18.     public void Post([FromBody]string value)  
  19.     {  
  20.     }  
  21.     // PUT api/values/5  
  22.     public void Put(int id, [FromBody]string value)  
  23.     {  
  24.     }  
  25.     // DELETE api/values/5  
  26.     public void Delete(int id)  
  27.     {  
  28.     }  
  29. } 

We are done with the models and controller part; now for the view as in the following:

  1. <header>  
  2.     <div class="content-wrapper">  
  3.         <div class="float-left">  
  4.             <p class="site-title">  
  5.                 <a href="~/">Text Box Auto Complete Sample</a></p>  
  6.         </div>  
  7.     </div>  
  8. </header>  
  9. <script src="~/Scripts/jquery-1.7.1.min.js"></script>  
  10. <script src="~/Scripts/jquery-ui-1.8.20.min.js"></script>  
  11. <div id="body">  
  12.     <input type="text" id="search" placeholder="Search for a Contact" required />  
  13.     <input type="submit" value="Go" id="submit" />  
  14. </div>  
  15. <script type="text/javascript">  
  16.       $('#search').autocomplete({  
  17.     source: function (request, response) {  
  18.         var autocompleteUrl = '/api/values';  
  19.         $.ajax({  
  20.             url: autocompleteUrl,  
  21.             type: 'GET',  
  22.             cache: false,  
  23.             dataType: 'json',  
  24.             success: function (json) {  
  25.                 // call autocomplete callback method with results   
  26.                 response($.map(json, function (data, id) {  
  27.                     return {  
  28.                         label: data.Role,  
  29.                         value: data.ItemId  
  30.                     };  
  31.                 }));  
  32.             },  
  33.             error: function (xmlHttpRequest, textStatus, errorThrown) {  
  34.                 console.log('some error occured', textStatus, errorThrown);  
  35.             }  
  36.         });  
  37.     },  
  38.     minLength: 2,  
  39.     select: function (event, ui) {  
  40.         alert('you have selected ' + ui.item.label + ' ID: ' + ui.item.value);  
  41.         $('#search').val(ui.item.label);  
  42.         return false;  
  43.     }  
  44. });  
  45. </script> 

Hit F5 to see the result.

AutoComplete Textbox in MVC
Image 2.
Select from AutoComplete Textbox in MVC

Image 3.


Similar Articles