Auto Complete TextBox Using jQuery and ASP.Net MVC

This article introduces approaches to show suggestions while typing into a field (Text Box) in an ASP.NET MVC project. It is possible by using the jQuery UI auto-complete method.

To start this task you need jQuery and the jQuery plugin libraries. You can download them from: https://jqueryui.com/. Download jquery.ui.autocomplete.js.

First of all open Visual Studio 2012 then select new project and click on ASP.NET MVC4 Web Application in Visual C#, name the project Autocomplete or whatever you like. Create a controller named HomeController and in this controller create an ActionResult method named Index.

  1. public class HomeController : Controller  
  2. {  
  3. //  
  4. // GET: /Home/  
  5. public ActionResult Index()  
  6. {  
  7. return View();  
  8. }  
  9. } 
Now create a view, right-click on the Index action method and select Add View and then click OK. Write the following code in this view to add a TextBox using the @html helper.
  1. @{  
  2.    ViewBag.Title = "Index";  
  3. }  
  4. <h2>Index</h2>  
  5. @Html.Label("Enter Your name")  
  6. @Html.TextBox("PassId") 

Now create an action on the controller that returns a list of suggestions. Here I am not using a database so I display static data using a select item list.

  1. [AcceptVerbs(HttpVerbs.Post)]  
  2. public JsonResult Autocomplete(string term)  
  3. {  
  4.       var result = new List<KeyValuePair<stringstring>>();  
  5.       IList<SelectListItem> List = new List<SelectListItem>();  
  6.       List.Add(new SelectListItem { Text = "test1", Value = "0" });  
  7.       List.Add(new SelectListItem { Text = "test2", Value = "1" });  
  8.       List.Add(new SelectListItem { Text = "test3", Value = "2" });  
  9.       List.Add(new SelectListItem { Text = "test4", Value = "3" });  
  10.       foreach (var item in List)  
  11.       {  
  12.          result.Add(new KeyValuePair<stringstring>(item.Value.ToString(), item.Text));  
  13.       }  
  14.       var result3 = result.Where(s => s.Value.ToLower().Contains(term.ToLower())).Select(w => w).ToList();  
  15.       return Json(result3, JsonRequestBehavior.AllowGet);  
  16. } 

Add a model for the get and set detailed information.

  1. namespace Autocomplete.Models  
  2. {  
  3.       public class DemoModel  
  4.       {  
  5.           public int id { getset; }  
  6.           public string name { getset; }  
  7.           public string mobile { getset; }  
  8.       }  
  9. } 

Now add another action result for the get detail information of the selected term by id. It takes a parameter name id. Using this id get detailed information about the selected item. It returns a JSON object of data. Now get data from JSON and append it to view the controls.

  1. [AcceptVerbs(HttpVerbs.Post)]  
  2. public JsonResult GetDetail(int id)  
  3. {  
  4.       DemoModel model = new DemoModel();  
  5.       // select data by id here display static data;  
  6.       if (id == 0)  
  7.       {  
  8.          model.id = 1;  
  9.          model.name = "Yogesh Tyagi";  
  10.          model.mobile = "9460516787";  
  11.       }  
  12.       else {  
  13.          model.id = 2;  
  14.          model.name = "Pratham Tyagi";  
  15.          model.mobile = "9460516787";  
  16.       }  
  17.       return Json(model);  
  18. } 

Now you need to add the following JavaScript code to your view that will be called the “autocomplete” method of the jQuery UI whenever you type any char into textBox. It has two methods, the first is source and the other is select. The source method calls when fire “keyup” event of TextBox. In the source method, we call the controller using Ajax. This controller method returns a list of suggestions.

When we select a suggestion from the list then another method “select” calls and it also calls the controller using Ajax and it returns the details of the selected suggestion.

  1. <script type="text/javascript">  
  2.     $("#PassId").autocomplete({  
  3.         source: function (request, response)  
  4.         {  
  5.             var customer = new Array();  
  6.             $.ajax({  
  7.                 async: false,  
  8.                 cache: false,  
  9.                 type: "POST",  
  10.                 url:  
  11.                "@(Url.Action("Autocomplete", "Home"))",  
  12.                 data: { "term": request.term  
  13.         },  
  14.         success: function (data) {  
  15.                     for (var i = 0; i <data.length ; i++) {  
  16.                         customer[i] = {label: data[i].Value, Id: data[i].Key };  
  17.                     }  
  18.                 }  
  19.             });  
  20.             response(customer);  
  21.         },  
  22.          select: function (event, ui) {  
  23.              //fill selected customer details on form  
  24.              $.ajax({  
  25.                  cache: false,  
  26.                  async: false,  
  27.                  type: "POST",  
  28.                  url:  
  29.                  "@(Url.Action("GetDetail", " Home"))",  
  30.                 data: { "id": ui.item.Id },  
  31.                 success: function (data) {  
  32.                 $('#VisitorDetail').show();             
  33.                 $("#Name").html(data.VisitorName)         
  34.                 $("#PatientName").html(data.PatientName)  
  35.                 //alert(data.ArrivingTime.Hours)  
  36.                 $("#VisitorId").val(data.VisitorId)  
  37.                 $("#Date").html(data.Date)  
  38.                 $("#ArrivingTime").html(data.ArrivingTime)  
  39.                 $("#OverTime").html(data.OverTime)  
  40.                      action = data.Action;  
  41.                 },  
  42.                 error: function (xhr,ajaxOptions, thrownError) {  
  43.                     alert('Failed to retrieve states.');  
  44.                 }  
  45.             });  
  46.         }  
  47.      });  
  48. </script> 
Now run your application and type “t” in the Text box; it looks like:



Select one item from the list, it will appear in the text box and it calls the “select” method of autocomplete that returns detailed information about the selected information.


If you have any queries then feel free to contact with me.


Similar Articles