Implement jQuery Autocomplete TextBox using Web API in ASP.Net MVC

essitco.dotnet
 
on Jul 26, 2021 03:54 AM
Sample_102219.zip
772 Views

Autocomplete not working when user is using mouse up and down arrows to select auto suggested option on search page and hit enter

This is my code

var apiurl = baseurls + "api/SearchTypeahead/Typeahead";
$(document).on("keydown.autocomplete", "#searchlist", function () {
    var charLength = $(this).val().length;
    if (charLength >= 3) {
        $(this).autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: apiurl,
                    dataType: "json",
                    data: {
                        term: request.term
                    },
                    success: function (data) {
                        response($.map(data, function (item) {
 
                            if (data.indexOf(item) === -1) {
                                return { name: "No Results." }
                            } else {
                                return {
                                    name: item
                                }
                            }
                        }))
 
                    }
                })
            },
            serarch: function () {
                $(".messagePopup").show();
                Loader();
            },
            focus: function (event, ui) {
                jQuery(event.target).val(ui.item.a);
                return false;
            },
            select: function (event, ui) {
                var name = ui.item.name.replace(" ", "-");
                window.location = "/" + name;
            },
            open: function () {
                //  $(".messagePopup").hide();
                $('li.ui-menu-item ').removeClass('ui-menu-item');
            },
 
        }).data("ui-autocomplete")._renderItem = function (ul, item) {           
            return $("<li></li>")
                .data("ui-autocomplete-item", item)
                .append("<a href='javascript:void(0)' style='font:12px'>" + item.name + "</a>")
                 
              .appendTo(ul);
        };

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jul 27, 2021 01:36 AM

Hi essitco.dotne...,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

Model

public class PersonModel
{
    public string Name { get; set; }
}

Web API Controller

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

public class AjaxAPIController : ApiController
{
    [Route("api/AjaxAPI/AjaxMethod")]
    [HttpPost]
    public List<System.Web.Mvc.SelectListItem> AjaxMethod(PersonModel person)
    {
        NorthwindEntities entities = new NorthwindEntities();
        List<System.Web.Mvc.SelectListItem> items = entities.Customers
            .Where(x => x.Country != null && x.ContactName.StartsWith(person.Name))
            .Select(x => new System.Web.Mvc.SelectListItem
            {
                Text = x.ContactName,
                Value = x.CustomerID
            }).ToList();

        return items;
    }
}

Controller

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

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
    <link rel="Stylesheet" type="text/css" href="https://code.jquery.com/ui/1.11.4/themes/start/jquery-ui.css" />
    <script type="text/javascript" src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
    <style type="text/css">
        .ui-menu .ui-menu-item a.ui-corner-all:hover,
        .ui-menu .ui-menu-item a.ui-corner-all:focus,
        .ui-menu .ui-menu-item a.ui-corner-all:active {
            background: #ff8a00 !important;
            color: #000;
            border-radius: 0;
        }

        .ui-state-hover, .ui-widget-content .ui-state-hover,
        .ui-widget-header .ui-state-hover, .ui-state-focus,
        .ui-widget-content .ui-state-focus, .ui-widget-header
        .ui-state-focus {
            background: #ff8a00;
            border: none;
            color: #000;
            border-radius: 0;
            font-weight: normal;
        }

        .ui-menu-item a {
            text-decoration: none;
            cursor: pointer;
        }
    </style>
</head>
<body>
    Name : <input id="txtName" type="text">&nbsp;&nbsp;&nbsp;<span id="lblResult"></span>
    <script type="text/javascript">
        $(function () {
            var apiUrl = "/api/AjaxAPI/AjaxMethod";
            $("#txtName").autocomplete({
                source: function (request, response) {
                    var person = '{Name: "' + request.term + '" }';
                    $.ajax({
                        type: "POST",
                        url: apiUrl,
                        data: person,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            if (data.length > 0) {
                                response($.map(data, function (item) {
                                    return {
                                        label: item.Text,
                                        val: item.Value
                                    }
                                }))
                            } else {
                                response([{ label: 'No results found.', val: -1 }]);
                                $('#lblResult').html('');
                            }
                        },
                        error: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                minLength: 3,
                search: function (event, ui) {
                    // Do your task.
                },
                focus: function (event, ui) {
                    jQuery(event.target).val(ui.item.label);
                    return false;
                },
                select: function (event, ui) {
                    // Do your task.
                    $('#lblResult').html('');
                },
                open: function (event, ui) {
                    // Do your task.
                    $('#lblResult').html($('.ui-autocomplete > li').length);
                },
                close: function (event, ui) {
                    // Do your task.
                    $('#lblResult').html('');
                }
            }).data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li></li>")
                    .data("ui-autocomplete-item", item)
                    .append("<a href='javascript:void(0)' style='font:10px'>" + item.label + "</a>")
                    .appendTo(ul);
            };
        });
    </script>
</body>
</html>

Screenshot