Saturday, June 26, 2021

Autocomplete | How to create autocomplete textbox search using asp .net MVC c# application | My 20 minutes study

June 26, 2021

Here is the link. 

In this tutorial I am going to implement autocomplete textbox for searching customer records using asp.net MVC c# application.  When the user enter for search customer, it suggests record for customer records in a dropdown menu.

Step 1: Here, I am using northwind database, Create an ADO.NET Entity Model and connect the database. We will be using Customer table for search records.

Step 2: Create a Controller name it as search and copy and paste the following code.

  Models db = new Models();
             
       public JsonResult GetCustomers(string term)

       {

           List<string> Customers = db.Customers.Where(s => s.ContactName.StartsWith(term))

               .Select(x =>x.ContactName).ToList();

           return Json(Customers, JsonRequestBehavior.AllowGet);
}

Step 4: Should refer the following code in required place and I am reffered in my Layout page.

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" /> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>

Step 5: Copy and paste the following code in the design page index.cshtml.

@{
   ViewBag.Title = "CUSTOMER SEARCH";
}
<br />
<br />
<br />

<script type="text/javascript">
   $(document).ready(function() {

      $("#txtSearch").autocomplete({

           source: '@Url.Action("GetCustomers","Search")',

           minLength: 1

       });
   });

</script>

<div class="form-group">
   SEARCH:
   @Html.TextBox("searchTerm",null, new { id = "txtSearch", Class = "autosuggest"})
</div>

RESULT:

autocomplete dropdown menu


No comments:

Post a Comment