Grouping data in autocomplete textbox using jquery in Asp.net MVC.


We can group data in autosuggest textbox in Asp.net MVC using jquery.

autosuggest

autosuggest

Add a input box in your View.


<div>
    @Html.TextBoxFor(m =&gt; m.Search_text, new { id = "Search_text", placeholder = "City, Airport, Place, Hotel Name", @class = "textWidth" })
</div>


Add model in your view. Creation of model will be done later.

@model MvcApplication1.Models.Search


Add style sheets in your view. we are referring some css and js files from jquery cdn.

<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="~/Css/StyleSheet.css" rel="stylesheet" />


Download this style sheet and add to your project and refer accordingly. Style Sheet Link
AutoSuggest.css
jQuery code for autocomplete input box. We have customized rendering part so that we can group result in input box. Grouping is done on the basis of category of content. Add this script into your view.

<script>
    $(function () {
        var searchText_Old = '';
        var CustomrenderMenu = function (Ul, item) {

            var Self = this;
            var Search_Category = null;
            var NodeCount = 0;
            $.each(item, function (index, item) {
                var li;

                if (item.category != Search_Category) {
                    Search_Category = item.category;
                    NodeCount = 1;
                    Ul.append("
&lt;li class=Header-" + Search_Category + "&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;" + Search_Category + "&lt;/li&gt;

");
                }
                li = Self._renderItemData(Ul, item);
                var liText = li.html();
                var SearchTerm = searchText_Old;
                var tag = 'b' || 'Strong',
                words = [SearchTerm] || [],
                regex = RegExp(words.join('|'), 'gi'),
                replacement = '&lt;' + tag + '&gt;$&amp;&lt;/' + tag + '&gt;';
                var liTextHighlighted = liText.replace(regex, replacement);
                li.html(liTextHighlighted);
                li.addClass("Content");
            });
            Ul.append("
&lt;li class=ui-last-line&gt;Keep typing your filter...&lt;/li&gt;

");
        };

        $('#Search_text').autocomplete({
            minlength: 3,
            source: function (request, response) {
                var SearchText = document.getElementById('Search_text').value;
                searchText_Old = SearchText;
                $('#Search_text').addClass('AutoSuggestLoader');
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    async: true,
                    url: "/Home/autoCompleteSearch",
                    data: "{Search_:'" + SearchText + "'}",
                    contentType: "application/json;characterset=utf-8",
                    success: function (result) {

                        $('#Search_text').removeClass('AutoSuggestLoader');
                        response(result);
                    },
                    error: function (result) {
                        debugger
                        $('#Search_text').removeClass('AutoSuggestLoader');
                        console.log(result);
                    }
                });
            },
            select: function (event, ui) {
                $('#Search_text').val(ui.item.label);
                return false;
            }
        })
        .focus(function () {
            $(this).autocomplete("search");
        })
        .autocomplete('instance')._renderMenu = CustomrenderMenu;
    });
</script>


Create a model class “Search” in your model folder. We have created four categories Hotel, city, airport and Place and create some dummy data.

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

namespace MvcApplication1.Models
{
    public class Search
    {
        public string label { get; set; }
        public string value { get; set; }
        public string category { get; set; }
        public string Search_text { get; set; }

        public List<string> GetCity()
        {
            List<string> objCity = new List<string>();
            objCity.Add("New Delhi");
            objCity.Add("Gurgaon");
            objCity.Add("Ghaziabad");
            objCity.Add("Mumbai");
            return objCity;
        }

        public List<string> GetAirport()
        {
            List<string> objAirport = new List<string>();
            objAirport.Add("Indira Gandhi International Airport");
            objAirport.Add("Santa Cruz Airport");
            objAirport.Add("Chhatrapati Shivaji International Airport");
            objAirport.Add("Bengaluru International Airport");
            return objAirport;
        }

        public List<string> GetPlace()
        {
            List<string> objPlace = new List<string>();
            objPlace.Add("Taj Mahal");
            objPlace.Add("Humayun's Tomb");
            objPlace.Add("Qutub Minar");
            objPlace.Add("akshardham");
            return objPlace;
        }

        public List<string> GetHotel()
        {
            List<string> objHotel = new List<string>();
            objHotel.Add("Taj Hotels");
            objHotel.Add("Oberoi Hotels");
            objHotel.Add("Redisson Hotels");
            objHotel.Add("Hyatt Hotels And Resorts");
            return objHotel;
        }


        public List<Search> SearchAutocomplete(string Search_)
        {
            List<Search> objSearchList = new List<Search>();
            List<string> objHotel = GetHotel().Where(h => h.ToUpperInvariant().Contains(Search_.ToUpperInvariant())).ToList();
            List<string> objCity = GetCity().Where(h => h.ToUpperInvariant().Contains(Search_.ToUpperInvariant())).ToList();
            List<string> objPlace = GetPlace().Where(h => h.ToUpperInvariant().Contains(Search_.ToUpperInvariant())).ToList();
            List<string> objAirport = GetAirport().Where(h => h.ToUpperInvariant().Contains(Search_.ToUpperInvariant())).ToList();
            foreach (var City in objCity)
            {
                objSearchList.Add(new Search { label = City, value = City, category = "City" });
            }
            foreach (var Airport in objAirport)
            {
                objSearchList.Add(new Search { label = Airport, value = Airport, category = "Airport" });
            }
            foreach (var Place in objPlace)
            {
                objSearchList.Add(new Search { label = Place, value = Place, category = "Place" });
            }
            foreach (var Hotel in objHotel)
            {
                objSearchList.Add(new Search { label = Hotel, value = Hotel, category = "Hotel" });
            }
            return objSearchList;
        }
    }
}


Create a controller file and put this code in your controller file. This Action return json format data.

[HttpPost]
public ActionResult autoCompleteSearch(string Search_)
{
    Search obj = new Search();
    return Json(obj.SearchAutocomplete(Search_), JsonRequestBehavior.AllowGet);
}

Note: We have used four images for category and one loader image.

airport

airport

autosuggestloader

autosuggestloader

city

city

hotel

hotel

place

place

One thought on “Grouping data in autocomplete textbox using jquery in Asp.net MVC.

Comments are closed.