user1025852
user1025852

Reputation: 2784

Auto-complete doesn't work as expected

I tried to implement this in MVC 5 with jquery ui 1.10.2

@{
    ViewBag.Title = "Home Page";
    Layout = null;
}


<p>
    Enter country name @Html.TextBox("Country")
    <input type="submit" id="GetCustomers" value="Submit" />
</p>

<span id="rData"></span>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
@Styles.Render("~/Content/themes/base/css")

<script type="text/javascript">
    $(document).ready(function () {
        $("#Country").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/AutoCompleteCountry",
                    type: "POST",
                    dataType: "json",
                    data: { term: request.term },
                    success: function(data) {
                        response($.map(data, function(item) {
                            return { label: item.Country, value: item.Country };
                        }));
                    }
                });
            }            
        });
    })
</script>

the server side is

 ...
            [HttpPost]
            public JsonResult AutoCompleteCountry(string term)
            {
                // just something to return..
                var list = new List<string>() { "option1", "option2", "option3"};

                var result = (from r in list
                    select r);

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

I have two issues 1. it open up drop down autocomplete with 3 dots but without the actual strings. 2. It has this annoying message of "3 results were found" - I'd like to eliminate it..

DO you have any idea how to face those two issues or neater way to implement it in MVC5?enter image description here

Upvotes: 0

Views: 439

Answers (2)

dtyler
dtyler

Reputation: 1428

The 3 bullet points and "3 results were found" is because you are missing the jQuery UI css file. That file will format a drop down that will look a lot better. You can customize how the dropdown looks with additional css.

Also, you are seeing 3 empty results because your JS is referencing item.Country ...

return { label: item.Country, value: item.Country };

But your server code is just sending 3 strings.

new List<string>() { "option1", "option2", "option3"};

To fix, change your JS to just reference the item (the string) ...

return { label: item, value: item};

OR, change your server code to send more complex objects

new List<Object>() { new { Country = "option1" }, new { Country = "option2" }, new { Country = "option3" } };

Upvotes: 1

rashmi
rashmi

Reputation: 1

use return data in place of return { label: item.Country, value: item.Country };

Upvotes: 0

Related Questions