Key Value Pair Auto complete TextBox In ASP.NET MVC

Some applications need to use an auto-complete text box with a key and value pair which populates the records with the combination of the key and its value when a user types into the text box.

The key value pair means suppose we need to populate records with employee Id along with his or her name or it may be anything as per your requirement. So let's demonstrate this requirement with the help of a sample ASP.NET MVC application.

Step 1 :
Create an ASP.NET MVC Application.
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
  3. Choose MVC empty application option and click on OK
Step 2: Add model class.

Right click on Model folder in the created MVC application and add class named Employee and write the following line of code,
Employee.cs
public class Employee
  {  
      public int Id { get; set; }  
      public string Name { get; set; }  
  
  }  
Step 3: Add user and admin controller

Right click on Controller folder in the created MVC application and add the controller class as:

Now after selecting the controller template, click the add button. Then another window appears, specifying the controller name and click the add button,


Now open the HomeController.cs file and write the following code into the Home controller class to bind and create the generic list from the model class as in the following,

HomeController.cs
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoCompleteInMVCJson.Models;

namespace AutoCompleteInMVCJson.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Index(string Prefix)
        {
            //Note : you can bind same list from database  
            List<Employee> ObjList = new List<Employee>()
            {

                new Employee {Id=100,Name="Vithal Wadje" },
                new Employee {Id=200,Name="Sudir Wadje" },
                new Employee {Id=300,Name="Sachin W" },
                new Employee {Id=400,Name="Vikram N" }


        };
            //Searching records from list using LINQ query  
            var EmpDet = (from N in ObjList
                          where N.Id.ToString().StartsWith(Prefix)|| N.Name.ToLower().StartsWith(Prefix.ToLower())
                          select new { N.Name, N.Id });
            return Json(EmpDet, JsonRequestBehavior.AllowGet);
        }
    }
}



In the above code, instead of going to database for records we are creating the generic list from model class and we will fetch records from above generic list.

Step 4:

Reference jQuery UI css and js library reference as there are many ways to add the reference of jQuery library into the our project. The following are some methods:
  • Using NuGet package manager , you can install library and reference into the project
  • Use CDN library provided by Microsoft, jQuery, Google or any other which requires active internet connection.
  • Download jQuery files from jQuery official website and reference into the project.
In this example we will use jQuery CDN library.

Step 5: 

Create jQuery Ajax function to call controller JSON action method and invoke autocomplete function,

<script type="text/javascript">
    $(document).ready(function () {
        $("#Name").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Id+"-"+item.Name, value: item.Id };
                        }))

                    }
                })
            }
            
        });
    })
</script>


To work above function don't forget to add the reference of the following jQuery CDN library as,

<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> 
Step 6:

Add view named index and put above json function into the view. After adding code necessary files and logic the Index.cshtml will look like the following,

Index.cshtml
@model AutoCompleteInMVCJson.Models.Employee
@{
    ViewBag.Title = "www.compilemode.com";
}
<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>
<script type="text/javascript">
    $(document).ready(function () {
        $("#Name").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Id+"-"+item.Name, value: item.Id };
                        }))

                    }
                })
            }
            
        });
    })
</script>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <hr />

        <div class="form-group">

            <div class="col-md-12">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

            </div>
        </div>

    </div>
}

Searching by Key or ID
 
Now run the application and type any key or Id then it will auto populate the records which exactly start with first key as in the following screenshot,



Searching by Name or Value

Now run the application and type any name then it will auto populate the records which exactly start with first word as in the following screenshot,


   
Selected Record 

Now select any key value pair , it will set the key in the textbox instead of value you may change vise versa .



From all the above examples, I hope you learned how to create the auto complete key value pair textbox using jQuery UI in ASP.NET MVC.
Note:
  • Perform changes in code as per your requirement  its just example .
  • Follow proper standards which might be not meet with this given code.
  • You need to use the jQuery library.
    Summary
    I hope this article is useful for all readers, If you have a suggestion then please contact me.

    Post a Comment

    www.CodeNirvana.in

    Protected by Copyscape
    Copyright © Compilemode