Autocomplete display data based on value in dropdownlist

Does anyone know how, or have any links on how to filter the data returned in a textbox that is based on the value of the selected item in a dropdownlist.

ie If a user selects hotel from a list, then when they start typing in the textbox only the address of the companies whos category matches hotel will appear using autocomplete.


I have added my server side code below, but I'm getting the following error.

public JsonResult FilterDirectorySearch(string searchText, string context)
        {
        var wq = DirectoryList(searchText,context).Select(a =>
           new { Location = a.strLocationSearch });
        return Json(wq.Distinct(), JsonRequestBehavior.AllowGet);
        }

    private List<DisplayDirectoryDataForSearchBox> DirectoryList(string searchString, string context)
        {
        var wq = _IGTDD.DisplayDirectoryData()
                  .Where(a => a.strLocationSearch.Contains(searchString, StringComparison.OrdinalIgnoreCase) && a.strCategory = context).ToList();
        return wq.ToList();
        }

Errors Error 1 Instance argument: cannot convert from 'string' to 'System.Linq.IQueryable'

Error 2 'string' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.Queryable.Contains(System.Linq.IQueryable, TSource, System.Collections.Generic.IEqualityComparer)' has some invalid arguments

Error 3 Argument 3: cannot convert from 'System.StringComparison' to 'System.Collections.Generic.IEqualityComparer'

Forgot to add this error for the code below

return (from x in wq where x.strLocationSearch.StartsWith(searchString, StringComparison.OrdinalIgnoreCase) && x.strCategory = context select x.strLocationSearch).AsEnumerable();

Error message: Error 1 Operator '&&' cannot be applied to operands of type 'bool' and 'string'


Any Autocomplete javascript tooling generally allows you to configure the source as a function, being either a javascript function and local data, or a function to an AJAX server source.

Within either the local javascript function or the remove AJAX responder, you can simply add the extra context data, by pulling the value from the required dropdown box.

Handling would then be either in the local javascript code or in the remote AJAX responder to deal with the extra information.

Without any context of what autocomplete coding you are using, it's difficult to illustrate my answer with code.

However, if you're using jQuery, Autocomplete UI and an AJAX function for the source:

$("#autocompleteTextBox").autocomplete({
    source: function(request, response) {
        var autocompleteContext = $("#dropdownBox").val();
        $.ajax({
            url: "http://source.com/searchJSON",
            dataType: "jsonp",
            data: {
                query: request.term,
                context: autocompleteContext
            },
            success: function(data) {
                ...

Note the two lines:

  • Where autocompleteContext variable is set, presumably from the dropbox you speak of
  • Where autocompleteContext is fed through to the searchJSON action in the data parameter
  • On the server-side (handler of searcjJSON) [C#/MVC psuedocode]:

    public List<string> searchJSON(string query, string context)
    {
       return (from x in db.SearchTable where x.Name.Contains(query) && x.context == context select x.Name).ToList()
    }
    

    If you're merely using a local array source in javascript, change to a function source, similar to the AJAX source...

    var fullArray = ["Apple", "Bat", "Cat", "Dog"];
    $("#autocompleteTextBox").autocomplete({
        source: function(request, response) {
            var autocompleteContext = $("#dropdownBox").val();
            response = //Code to filter fullArray with request.term and autocompleteContext here
        }
    

    这是完全功能的客户端示例:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
        <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
        <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css" />
        <script type="text/javascript">
            if (!Array.prototype.filter) {
                Array.prototype.filter = function (fun /*, thisp */) {
                    "use strict";
    
                    if (this == null)
                        throw new TypeError();
    
                    var t = Object(this);
                    var len = t.length >>> 0;
                    if (typeof fun != "function")
                        throw new TypeError();
    
                    var res = [];
                    var thisp = arguments[1];
                    for (var i = 0; i < len; i++) {
                        if (i in t) {
                            var val = t[i]; // in case fun mutates this
                            if (fun.call(thisp, val, i, t))
                                res.push(val);
                        }
                    }
    
                    return res;
                };
            }
    
            $(function () {
                var availableAddresses = [
                    "New York Hotel",
                    "London Restaurant",
                    "London Hotel",
                    "Paris Restaurant",
                    "Berlin Restaurant",
                    "Moscow Restaurant"
                ];
                $("#businesses").keyup(function () {
                    $("#businesses").autocomplete({
                        source: availableAddresses.filter(function (element, index, array) {
                            return (element.toLowerCase()
                                .indexOf($("#filter").val().toLowerCase()) !== -1);
                        })
                    });
    
                });
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <select id="filter">
                    <option>hotel</option>
                    <option>restaurant</option>
                </select>
                <input type="text" id="businesses"/>
            </div>
        </form>
    </body>
    </html>
    
    链接地址: http://www.djcxy.com/p/75250.html

    上一篇: 子查询在LINQ语句的Where子句中

    下一篇: 根据下拉列表中的值自动完成显示数据