Search code examples
javascriptjqueryasp.net-mvcautocompletejquery-ui-autocomplete

Jquery UI autocomplete from two data sources in Asp.net MVC5


I am working on a ASP.net MVC5 (C#) web application am trying to show autocomplete data from two different tables (one is device table and other one is news table) in a div in single textbox like phonearena.com is showing, when you input a query they show all the phones and tablets containing that query and also the news and reviews. enter image description here

right now I am able to autocomplete data from one datasource like this.

$(function () {
function log(message) { }

$("#search_input").autocomplete({
    source: "/Search/?term",
    minLength: 1,
    select: function (event, ui) {
        $("#mobile").val(ui.item.title);
        $("#mobile-query").val(ui.item.query);
        return false;
    }
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
    return $("<li>")
    .append("<a href='/" + item.query + "'>" + item.title + "</a>")
    .appendTo(ul);
};

});

I want to show devices and news lists in a div. Please see on the site I mentioned about and write any famous phone, and drop down div will pop out with records. Can you guys please help me figuring this out. Thanks

Tables Structure

Device Table

Device_Id-----Device_Name-----Device_Query

1-----------------iPhone 6---------------iphone_6

2-----------------Galaxy S6--------------galaxy-s6

3-----------------Lumia 990--------------lumia_990

News Table

News_id------News_Title---------------News_Query----------------Device_Id

1-----------iPhone 6 Review---------------iphone-6-review----------------------1

2-----------iPhone 6 Pros & Cons----------iphone-6-pros-cons----------------1

3-----------Lumia 990 Camera Review-------lumia-990-camera-review-----3


Solution

  • for this you can create two queries with same column names and union it like :

    select device_name as title, device_query as query, 'device' as q_type from device_table // add your where clause here
    
    union 
    
    select news_title as title, news_query as query, 'news' as q_type from news_table // add your where clause here
    

    and in autocomplete

    .data("ui-autocomplete")._renderItem = function (ul, item) {
    
    if(item.q_type == "device")
    {
    // add your device type html
    }
    else
    {
     // add your news type html
    }
    };