navigation
asp.net MVC

How to implement Autocomplete textbox in asp.net MVC?

| | ASP-NET , CSharp , Html , JQuery , MVC

In this article we will discuss implementing autocomplete functionality in asp.net MVC application using jQuery Autocomplete widget.

We will be using employee table

Step 1: Create a table using the following script with data:

USE[ShoppingZone]

GO

/******Object:  Table [dbo].[Employee]    Script Date: 04/21/2016 13:42:12 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE TABLE [dbo].[Employee](

      [EmployeeID] [int] IDENTITY(1,1) NOT NULL,

      [Name] [nvarchar](50) NULL,

      [Gender] [nvarchar](50) NULL,

      [City] [nvarchar](50) NULL,

 CONSTRAINT[PK_tbl_Employee] PRIMARY KEY CLUSTERED

(

      [EmployeeID] 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

SET IDENTITY_INSERT [dbo].[Employee]ON

INSERT [dbo].[Employee] ([EmployeeID], [Name], [Gender], [City]) VALUES (1, N'Thivan', N'male', N'tirunelveli')

INSERT [dbo].[Employee] ([EmployeeID], [Name], [Gender], [City]) VALUES (2, N'Rasik', N'male', N'Tuticorin')

INSERT [dbo].[Employee] ([EmployeeID], [Name], [Gender], [City]) VALUES (3, N'Usman', N'male', N'tirunelveli')

INSERT [dbo].[Employee] ([EmployeeID], [Name], [Gender], [City]) VALUES (4, N'karishma', N'female', N'mumbai')

INSERT [dbo].[Employee] ([EmployeeID], [Name], [Gender], [City]) VALUES (5, N'chaitrali', N'female ', N'mumbai')

INSERT [dbo].[Employee] ([EmployeeID], [Name], [Gender], [City]) VALUES (6, N'mansoor', N'male', N'gujarat')

INSERT [dbo].[Employee] ([EmployeeID], [Name], [Gender], [City]) VALUES (7, N'mydeen', N'male', N'chennai')

SET IDENTITY_INSERT [dbo].[Employee]OFF

 

Step 2: Create an ado.net entity data model using table Employee and generate entity for that.

Step 3: Right click on the "Controllers" folder and add "Employee" controller. Copy and paste the following code. Please make sure to include "MVC_tutorials.Models" namespace.

using MVC_tutorials.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace MVC_tutorials.Controllers

{

    public class EmployeeController : Controller

    {

        models db = new models();

 

        public ActionResult Index()

        {

            return View(db.Employees);

        }

 

        [HttpPost]

        public ActionResult Index(string searchTerm)

        {

         

            List<Employee> Employees;

            if (string.IsNullOrEmpty(searchTerm))

            {

                Employees =db.Employees.ToList();

            }

            else

            {

                Employees = db.Employees

                    .Where(s =>s.Name.StartsWith(searchTerm)).ToList();

            }

            return View(Employees);

        }

 

        public JsonResult GetEmployees(string term)

        {

            List<string> Employees = db.Employees.Where(s =>s.Name.StartsWith(term))

                .Select(x =>x.Name).ToList();

            return Json(Employees, JsonRequestBehavior.AllowGet);

        }

 

    }

}

 

Step 4: Right click on the "Index" action method in the "EmployeeController" and add "Index" view. Copy and paste the following code.

@modelIEnumerable<MVC_tutorials.Models.Employee>

@{

    ViewBag.Title = "AutoComplete example";

}

 

 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

  <script src="//code.jquery.com/jquery-1.10.2.js"></script>

  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

   

 

<h2>AutoComplete example</h2>

<script type="text/javascript">

    $(function () {

        $("#txtSearch").autocomplete({

            source: '@Url.Action("GetEmployees","Employee")',

            minLength: 1

        });

    });

</script>

 

<div style="font-family:Arial">

 

@using (@Html.BeginForm())

{

    <b>Name: </b>

    @Html.TextBox("searchTerm", null, new { id = "txtSearch" })

    <input type="submit" value="Search" />

}

 

<table border="1">

    <tr>

        <th>

            @Html.DisplayNameFor(model => model.Name)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.Gender)

        </th>

      

    </tr>

 

@foreach (var item in Model)

{

    <tr>

        <td>

            @Html.DisplayFor(modelItem => item.Name)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.Gender)

        </td>

    

    </tr>

}

</table>



</div>