When creating a web-application, you may need a textbox which can show suggestions to user on some data input by user, so in this post I have explained how you can implement jquery ui autocomplete feature in ASP.NET MVC.

Step 1: Create a table in database which we will use for jquery autocomplete example, suppose I have the below EmployeeDetails Database and table with employee data in table as shown below in the image

sql-server-table-sample-for-jquery-auto-complete-mvc-min.png

We will be using above table "EmpName" coluumn to show suggestions to user when using jQuery Autocomplete

Step 2: Create a new project in your Visual studio, by navigating to File-> New -> Project -> Select "ASP.NET web-application" -> Name your application ( jQueryAutocompleteMVC) and click "OK"

Select MVC as template and let visual studio generate the template files.

Step 3: Connect your web-application to database using Entity framework, I am using ADO.NET for this pupose

You will need to add Entity Data Model to your project by right clicking the Solution Explorer and then click on Add and then New Item option of the Context Menu.

From the Add New Item window, select ADO.NET Entity Data Model and set its Name as jQueryAutoCompleteModel and then click Add.

Then the Entity Data Model Wizard will open up where you need to select EF Designer database option.

Now the wizard will ask you to connect and configure the Connection String to the database, click on "New Connection" button on top right side, select

  1. SQL Server Instance
  2. Database

And then click Test Connection to make sure all settings are correct. ( I am not explaining the details process here, if you need to know how to connect to database, you can look into this post MVC tutorial part-2 connecting to database, fetching/inserting data )

Once you are connected to database using Entity framework / ADO.NET, you will see edmx file in your Models Folder as below

Step 4: Go to HomeController.cs inside Controllers folder and write the code below, which we will be using to Get Employee names from database and pass it as JSON to Front-end Ajax call.

        EmployeeDetailsEntities db = new EmployeeDetailsEntities();
        [HttpPost]
        public JsonResult GetEmpName(string Prefix)
        {

            var Countries = (from c in db.EmpDetails
                             where c.EmpName.StartsWith(Prefix)
                             select new { c.EmpName });
            return Json(Countries, JsonRequestBehavior.AllowGet);
        }

so complete HomeController.cs code will be as below

using jQueryAutoCompleteMVC.Models;
using System.Linq;
using System.Web.Mvc;

namespace jQueryAutoCompleteMVC.Controllers
{
    public class HomeController : Controller
    {
        EmployeeDetailsEntities db = new EmployeeDetailsEntities();

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult GetEmpName(string Prefix)
        {

            var Countries = (from c in db.EmpDetails
                             where c.EmpName.StartsWith(Prefix)
                             select new { c.EmpName });
            return Json(Countries, JsonRequestBehavior.AllowGet);
        }
    }
}

Step 5: Go to your Index.cshtml View inside Views->Home Folder, and use the below razor code to show Textbox and use the jQuery UI Autocomplete to get employee name suggestions

 @model jQueryAutoCompleteMVC.Models.EmpDetail
    @{
        ViewBag.Title = "Home Page";
    }
<br/>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/start/jquery-ui.css">

    <div class="form-group ">
        @Html.LabelFor(model => model.EmpName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-4">
            @Html.TextBoxFor(model => model.EmpName, htmlAttributes: new { @class = "form-control" })
        </div>
    </div>
    @section scripts{


        <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
        <script>
            $(document).ready(function () {
                $("#EmpName").autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            url: "/Home/GetEmpName",
                            type: "POST",
                            dataType: "json",
                            data: { Prefix: request.term },
                            success: function (data) {
                                response($.map(data, function (item) {
                                    return { label: item.EmpName, value: item.EmpName };
                                }))

                            }
                        })
                    },
                    messages: {
                        noResults: "",
                        results: function (count) {
                            return count + (count > 1 ? ' results' : ' result ') + ' found';
                        }
                    }
                });
            })
        </script>

    }  

You can see in the above Razor code, we are referring jQuery UI files from CDN

Also, we have added code using jQuery to call C# Controller code "GetEmpName" using Ajax.

We are sending terms to be searched to C# controller using "data: {Prefix: request.Term}" in jQuery Ajax  POST request, in the response from controller, we are looping data using $.map

@section scripts is used to as we are already referencing jQuery using MVC default bundle's in _Layout.cshtml.

After running and building the project you must see output as below

jquery-autocomplete-4-min.png

Here is the Gif Sample of the output

jquery-autocomplete-mvc-c-sharp-min.gif

You can download the sample project.

You may also like to read:

Using Google Charts in ASP.NET MVC (With Example)

Send data to MVC C# controller using jQuery Ajax

jQuery Datatable implementation in MVC C#

Check database size in Sql server ( Various Ways explained)