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

Image 1.
This is my Portal database script.
- USE [Portal]
- GO
- /****** Object: Table [dbo].[Portal_Contacts] Script Date: 11/14/2013 09:13:44 ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE TABLE [dbo].[Portal_Contacts](
- [ItemID] [int] IDENTITY(0,1) NOT NULL,
- [ModuleID] [int] NOT NULL,
- [CreatedByUser] [nvarchar](100) NULL,
- [CreatedDate] [datetime] NULL,
- [Name] [nvarchar](50) NULL,
- [Role] [nvarchar](100) NULL,
- [Email] [nvarchar](100) NULL,
- [Contact1] [nvarchar](250) NULL,
- [Contact2] [nvarchar](250) NULL,
- CONSTRAINT [PK_Contacts] PRIMARY KEY NONCLUSTERED
- (
- [ItemID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
Now add a connection string in the web.config fle as in the following:
- <connectionStrings>
- <add name="PortalConnectionString" connectionString="Data Source=.;Initial Catalog=Portal;Integrated Security=True" providerName="System.Data.SqlClient" />
- </connectionStrings>
Now add model classes as in the following:
- public class PortalContacts
- {
- public int ItemId { get; set; }
- // public string Name { get; set; }
- public string Role { get; set; }
- //public string Email { get; set; }
- //public string Contact1 { get; set; }
- //public string Contact2 { get; set; }
- }
The following is my repository class:
- public class PortalContactsRepository
- {
- public IEnumerable<PortalContacts> GetContacts()
- {
- using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["PortalConnectionString"].ConnectionString))
- {
- connection.Open();
- using (SqlCommand command = new SqlCommand(@"SELECT [ItemID]
- ,[Name]
- ,[Role]
- ,[Email]
- ,[Contact1]
- ,[Contact2]
- FROM [Portal].[dbo].[Portal_Contacts]", connection))
- {
- // Make sure the command object does not already have
- // a notification object associated with it.
- command.Notification = null;
- if (connection.State == ConnectionState.Closed)
- connection.Open();
- using (var reader = command.ExecuteReader())
- return reader.Cast<IDataRecord>()
- .Select(x => new PortalContacts()
- {
- ItemId = x.GetInt32(0),
- // Name = x.GetString(1),
- Role = x.GetString(2),
- //Email = x.GetString(3),
- //Contact1 = x.GetString(4),
- //Contact2 = x.GetString(5)
- }).ToList();
- }
- }
- }
- }


Join the conversation! Your thoughts help the community grow.