Auto Complete TextBox Using jQuery and ASP.NET MVC

Here we will see how to use JQuery autocomplete functionality in ASP.NET MVC. Application is going to have two entities [employee and department]. On typing names of employee in text box a auto-generated list of names starting with the search text would appear and on clicking any of the name from list the corresponding department and employee name will be shown on page.

Following are the steps to be followed:

Step 1) Create a new project [ASP.NET MVC4 Web Application] and provide the appropriate name [Ex AutoCompleteMVC]. Choose MVC empty application option and click on OK.

Step 2) Create Model Classes

Go to Model folder and right click to add class [Employee.cs] and [Department.cs].

[Employee.cs]

 public class Employee  
 {  
    public int Empid { get; set; }  
    public string Name { get; set; }          
    public int Deptid { get; set; }  
 }  

[Department.cs]

 public class Department  
 {  
    public int Deptid { get; set; }      
    public string Name { get; set; }  
 }  

Step 3) Create a data repository which will have a static list of employees and corresponding departments. [DataLibrary.cs]

 public static class DataLibrary  
 {  
   public static List<Employee> employees  
   {  
     get  
     {  
        return new List<Employee>{  
                      new Employee{Empid=1,Name="Aakash",Deptid=1},  
                      new Employee{Empid=2,Name="Ashwin",Deptid=1},  
                      new Employee{Empid=3,Name="Jorge",Deptid=1},  
                      new Employee{Empid=4,Name="Dilip",Deptid=6},  
                      new Employee{Empid=5,Name="Bihal",Deptid=5},  
                      new Employee{Empid=6,Name="Suresh",Deptid=4},  
                      new Employee{Empid=7,Name="Taylor",Deptid=2},  
                      new Employee{Empid=8,Name="Sedan",Deptid=3},  
                      new Employee{Empid=9,Name="Reena",Deptid=2},  
                      new Employee{Empid=10,Name="Anthony",Deptid=1},  
                      new Employee{Empid=11,Name="Mike",Deptid=2},  
                      new Employee{Empid=12,Name="Jones",Deptid=1}  
                      };  
      }  
    }  
    public static List<Department> departments  
    {  
      get  
      {  
        return new List<Department>{  
                      new Department{Deptid=1,Name="Sales"},  
                      new Department{Deptid=2,Name="Financial"},  
                      new Department{Deptid=3,Name="Marketing"},  
                      new Department{Deptid=4,Name="HR"},  
                      new Department{Deptid=5,Name="Accounts"},  
                      new Department{Deptid=6,Name="Labour"}  
                      };  
      }  
    }  
  }  

Step 4) Create Controller

Go to Controllers folder and right click to add controller [EmployeeController.cs].

 public class EmployeeController : Controller  
   {  
     public ActionResult Index()  
     {  
       return View();  
     }  
     public JsonResult getAutoCompleteData(string prefix)  
     {  
       List<dynamic> getNames = DataLibrary.employees.Where(item => item.Name.ToLower().StartsWith(prefix.ToLower())).Select(x => new { Name = x.Name, Id = x.Empid }).ToList<dynamic>();  
       // Return the result set as JSON  
       return Json(getNames, JsonRequestBehavior.AllowGet);  
     }  
     public JsonResult getDetails(string empid)  
     {  
       List<dynamic> getEmpDetails = new List<dynamic>();  
       Employee empDetail = DataLibrary.employees.Where(item => item.Empid.ToString() == empid).FirstOrDefault<Employee>();  
       getEmpDetails.Add(new { name = empDetail.Name,  
         department = (DataLibrary.departments.Where(item => item.Deptid == empDetail.Deptid).Select(x => new { department = x.Name }.department )) });  
       // Return the result set as JSON  
       return Json(getEmpDetails, JsonRequestBehavior.AllowGet);  
     }  
   }  

In controller we have an default Index method and two other methods.

getAutoCompleteData(string prefix) – This method will be called for autocomplete list to be generated with prefix. It will match the employees starting with the required prefix and return a Json list of employee names and id.

getDetails(string empid) – This method will be called after selecting an employee from the generated list. It will take Employee id(empid) as a input and return an Json object consisting employee name and department.

Step 5) Create following JavaScript code [ jQuery Ajax function ] to invoke controller JSON action method.

Following code will invoke controller JSON action method [i.e getAutoCompleteData and getDetails]. JavaScript code will have an autocomplete function which will be called when you type any char in Textbox. It has two methods . Source method will be called on keyup event of textbox. It will call controller method [getAutoCompleteData] which will return a list of employee names along with their Id. After selecting any name from the list Select method will be called which will call controller method [getDetails] and return employee name and department which will be displayed in view.

"text/javascript">
    $(document).ready(function () {
        $('#VisitorDetail').hide();
        var Employee = new Array();
        $('#EmpName').autocomplete({
            source: function (request, response) {
                $.getJSON("/Employee/getAutoCompleteData?prefix=" + request.term, function (data) {
                    for (var i = 0; i function (event, ui) {
                $.ajax({
                    type: "POST",
                    url: "@(Url.Action("getDetails", "Employee"))",
                    data: { "empid": ui.item.Id },
                    success: function (data) {
                        $('#VisitorDetail').show();
                        $("#Name").html(data[0].name)
                        $("#Department").html(data[0].department)
                        action = data.Action;
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert('Failed to retrieve states.');
                    }
                });
            },
            delay: 100
        });
    });

Step 6) Add default view named index in Views->Employee folder and put above javascript function in it. The final copy of index.cshtml will look like below

Index File

Step 7) Save and run the application. Typle any character [Ex. ‘A’] and it will populate employee names which exactly start with the entered character

MVC auto complete

Step 8) select any one name from the generated list and it will return the department and employee name.

Auto complete MVC application

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s