, , , ,

How to do Autocomplete search after 3 characters are entered using C# MVC

Posted by

Sure! Here’s an example of how you can implement autocomplete search functionality using a dropdown list in an MVC framework application:

  1. In your View (.cshtml file), add the following code to create the dropdown list with autocomplete functionality:
@using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
    @Html.TextBox("searchInput", null, new { id = "searchInput", placeholder = "Enter search term" })
    @Html.DropDownList("searchResults", new SelectList(null, "Id", "Name"), "Select an option", new { id = "searchResultsDropdown" })
}
  1. Add the necessary JavaScript code to your View to handle the autocomplete functionality. Place this code within a <script> tag or in a separate JavaScript file:
$(document).ready(function () {
    $("#searchInput").keyup(function () {
        var searchTerm = $(this).val();
        if (searchTerm.length >= 3) {
            $.ajax({
                url: "@Url.Action("AutocompleteSearch", "Home")",
                type: "GET",
                data: { searchTerm: searchTerm },
                success: function (data) {
                    var dropdown = $("#searchResultsDropdown");
                    dropdown.empty();
                    if (data.length > 0) {
                        $.each(data, function (index, item) {
                            dropdown.append($('<option></option>').val(item.Id).text(item.Name));
                        });
                    } else {
                        dropdown.append($('<option></option>').text("No results found"));
                    }
                }
            });
        }
    });
});
  1. In your Controller (HomeController.cs), add the following action methods to handle the autocomplete search functionality:
public class HomeController : Controller
{
    // Other action methods...

    [HttpGet]
    public JsonResult AutocompleteSearch(string searchTerm)
    {
        // Implement your search logic here based on the searchTerm
        // Retrieve the search results from your data source

        // For demonstration purposes, returning dummy data
        var results = new List<SearchResult>
        {
            new SearchResult { Id = 1, Name = "Result 1" },
            new SearchResult { Id = 2, Name = "Result 2" },
            new SearchResult { Id = 3, Name = "Result 3" }
        };

        return Json(results, JsonRequestBehavior.AllowGet);
    }
}

public class SearchResult
{
    public int Id { get; set; }
    public string Name { get; set; }
}
  1. Customize the AutocompleteSearch action method to implement your specific search logic. In this example, we are returning dummy data, but you can replace it with your actual search implementation.
  2. Make sure you have included the necessary JavaScript libraries (e.g., jQuery) in your View for the autocomplete functionality to work.

That’s it! With these steps, you should have autocomplete search functionality on your dropdown list. When a user enters at least 3 characters in the search input, an AJAX call is made to the AutocompleteSearch action method in the controller, which retrieves search results based on the search term. The results are then dynamically populated in the dropdown list.