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.

public class HomeController : Controller
{

//
// GET: /Home/
public ActionResult Index()
{
return View();
}
}

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.

@{
   ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.Label("Enter Your name")
@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.

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Autocomplete(string term)
{
      var result = new List<KeyValuePair<string, string>>();
      IList<SelectListItem> List = new List<SelectListItem>();
      List.Add(new SelectListItem { Text = "test1", Value = "0" });
      List.Add(new SelectListItem { Text = "test2", Value = "1" });
      List.Add(new SelectListItem { Text = "test3", Value = "2" });
      List.Add(new SelectListItem { Text = "test4", Value = "3" });
      foreach (var item in List)
      {
         result.Add(new KeyValuePair<string, string>(item.Value.ToString(), item.Text));
      }
      var result3 = result.Where(s => s.Value.ToLower().Contains(term.ToLower())).Select(w => w).ToList();
      return Json(result3, JsonRequestBehavior.AllowGet);
}

Add a model for the get and set detailed information.

namespace Autocomplete.Models

{
      public class DemoModel
      {
          public int id { get; set; }
          public string name { get; set; }
          public string mobile { get; set; }
      }
}

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.

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetDetail(int id)
{
      DemoModel model = new DemoModel();
      // select data by id here display static data;
      if (id == 0)
      {
         model.id = 1;
         model.name = "Yogesh Tyagi";
         model.mobile = "9460516787";
      }
      else {
         model.id = 2;
         model.name = "Pratham Tyagi";
         model.mobile = "9460516787";
      }
      return Json(model);
}

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.

<script type="text/javascript">
    $("#PassId").autocomplete({
        source: function (request, response)
        {
            var customer = new Array();
            $.ajax({
                async: false,
                cache: false,
                type: "POST",
                url:
               "@(Url.Action("Autocomplete", "Home"))",
                data: { "term": request.term
        },
        success: function (data) {
                    for (var i = 0; i <data.length ; i++) {
                        customer[i] = {label: data[i].Value, Id: data[i].Key };
                    }
                }
            });
            response(customer);
        },
         select: function (event, ui) {
             //fill selected customer details on form
             $.ajax({
                 cache: false,
                 async: false,
                 type: "POST",
                 url:
                 "@(Url.Action("GetDetail", " Home"))",
                data: { "id": ui.item.Id },
                success: function (data) {
                $('#VisitorDetail').show();           
                $(
"#Name").html(data.VisitorName)       
                $(
"#PatientName").html(data.PatientName)
                //alert(data.ArrivingTime.Hours)
                $("#VisitorId").val(data.VisitorId)
                $("#Date").html(data.Date)
                $("#ArrivingTime").html(data.ArrivingTime)
                $("#OverTime").html(data.OverTime)
                     action = data.Action;
                },
                error: function (xhr,ajaxOptions, thrownError) {
                    alert('Failed to retrieve states.');
                }
            });
        }
     });
</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 query than feel free to contact with me.