Combo box with search

Asked

Viewed 628 times

3

I need to create a combobox that allows the administrator to search the user and that while the administrator searches, already appear within the combo some options that are similar to what was typed. Also, after finding the searched user, the administrator must click on the selected option, and below it, display all user data.

Does anyone know if it is possible to do it? If yes, they could post an example, even if it is simple to apply?

  • Something like that? http://jqueryui.com/autocomplete/

  • Yes! But I need to populate this combo box with the database data, and then display the selected data in a grid/form below...

1 answer

4


To implement Autocomplete, you will need to install the following package:

https://www.nuget.org/packages/jquery.ui.combined/

Suppose a TextBox with Autocomplete that brings cities, and automatically fills a state according to the state id. I need to have in my View the city fields, state, Hidden Fields and the script that makes it all work:

@Html.HiddenFor(model => model.CityID)
@Html.HiddenFor(model => model.StateID)
@Html.EditorFor(model => model.CityName)
@Html.TextBoxFor(model => model.StateName, new { disabled = "disabled", @readonly = "readonly" })

<script type="text/javascript">
    $(function () {
        $("#CityName").autocomplete({
            source: '@Url.Action("AjaxFindByName", "Cities")',
            minLength: 3,
            select: function (event, ui) {
                $("#CityName").val(ui.item.value);
                $("#CityID").val(ui.item.CityID);
                $("#StateName").val(ui.item.StateName);
                $("#StateID").val(ui.item.StateID);

                return false;
            }
        });
    });
</script>

In Controller, we need to have a Action that returns a JSON to populate the information from Autocomplete, receiving a term as a parameter (term in this case it is standard jQuery UI, and means it is part of the name of the city in this context):

    public JsonResult AjaxFindByName(string term)
    {
        var cities = context.Cities
            .Include(c => c.State)
            .Where(c => c.Name.ToUpper().Contains(term.ToUpper())).Take(10)
            .AsEnumerable()
            .Select(c => new
            {
                value = c.Name,
                CityID = c.CityID,
                StateName = c.State.Name,
                StateID = c.StateID
            });

        return Json(cities, JsonRequestBehavior.AllowGet);
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.