Jquery Autocomplete text box in MVC

How to implement Jquery autocomplete in MVC

Autocomplete texts boxes are very useful when a user searches on the website. Jquery autocomplete function suggests the already available data to the user and minimize the time for the search.

Jquery autocomplete
Jquery autocomplete

I have created a new controller for this and added a view. In the controller we have two action methods for Get and Call

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AutoComplete.Controllers
{
public class AutoCompleteController : Controller
{
List<string> personList = new List<string>(new string[] { "Alex", "David", "John" ,"Jonny" });

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

[HttpPost]
public JsonResult Index(string term)
{
var element = personList.Where(item => item.ToLower().StartsWith(term.ToLower()));

return Json(element.ToList(), JsonRequestBehavior.AllowGet);
}
}
}

For this example project Im using only a string list as the data source. In an actual implementation you can use any complex data source for this Jquery autocomplete function.

In the Get method we are just returning the View and inside the view we should have a form and an input box to type the search key words.  Post method we have the functionality implemented and from Jquery we are going to pass the search term to this post method.

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

<div class="form-horizontal">

<hr />

<div class="form-group">

<div class="col-md-12">
<input class = "form-control" type="text" value="" id="searchterm" name="term" placeholder="Type here.."/>
</div>
</div>

</div>
}

Then we have to use the Jquery for this function. first we have to add the references for the required libraries. First add the reference to jquery library and then add the reference to jquery-ui library. Jquery autocomplete uses one of the methods from jquery-ui library. If jquery-ui is not included in the project, you can install it from the nuget packages. Then we have to write the jquery POST call to the controller to get the autocomplete terms.

This is not the best practice to add the reference in the view itself and write the scripts inside the View. You can check how to add separate javascript files to a project from here

Add a View

This is the view

@model string
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-1.12.4.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />

<script>
$(document).ready(function () {

$('#searchterm').autocomplete(
{
source: function (request, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: "/AutoComplete/Index",
data: { term: request.term },
success: function (data) {
response(data);
},
error: function (message) {
response([]);
}
});
},
});
})
</script>
<h2>Index</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">

<hr />

<div class="form-group">

<div class="col-md-12">
<input class = "form-control" type="text" value="" id="searchterm" name="term" placeholder="Type here.."/>
</div>
</div>

</div>
}

Now you can run the project and check the functionality. Please don’t forget to remove if there any breakpoints in the code. Otherwise you can’t see the suggestions.

Sajith Dilhan on FacebookSajith Dilhan on Linkedin
Sajith Dilhan
Software Developer at Sana Commerce

Leave a Reply

Your email address will not be published. Required fields are marked *