Combo box with search

2

I need to create a combobox that allows the administrator to search the user and that while the administrator is searching, some options that are similar to the one that has been entered appear within the combo. In addition, after finding the user searched, the administrator must click on the selected option, and underneath it, display all the user data.

Does anyone know if it's possible? If yes, could you post an example, even if simple from the application?

    
asked by anonymous 08.09.2014 / 02:53

1 answer

3

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

  

link

Assume a TextBox with Autocomplete that brings cities, and automatically populate a state according to the state Id. I need to have in my View the city, 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>

On the Controller, we need to have a Action that returns a JSON to populate the Autocomplete information, getting term as a parameter ( term in this case is jQuery UI default, and means that it is part of the city name 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);
    }
    
08.09.2014 / 03:49