Autocomplete

autocomplete.png
The autocomplete makes a textbox with autocomplete functionality and a hidden input where the id of the selected item is stored (if there is any ids).

you call it like this:
@Html.Autocomplete("Person")
//or like this
@Html.AutocompleteFor(o => o.Show)

You can specify the name of the hidden input in the propId helper parameter or by changing the convention from the Settings.Autocomplete.IdFormat, by default is '{0}Id'.
Just like the AjaxDropdown it requires a controller and has an attribute for using it with EditorFor helper.

The controller must have a search action that should return a Json made from IEnumerable<IdTextItem> (if you don't need ids just don't set them):
public ActionResult Search(string searchText, int maxResults)
{
    return Json(repo.GetAll().Select(o => new IdTextItem {Id = o.Id, Text = o.Name}));
}

It has ParentId and Data ("many parents") functionality like the AjaxDropdown, except here when the value of a parent is changed the value of the autocomplete is not changed.

To make it not generate the hidden input you can specify generatePropId:false (needed for the html.EditorFor) and put the html.HiddenFor manually.

Example

autocomplete controller which also uses a parentId
    public class PersonAutocompleteController : Controller
    {
        public JsonResult Search(string searchText, int maxResults, int? parent)
        {
...
            return Json(source.Where(o =>
                                     (o.Name).Contains(searchText))
                                     .Select(p => new IdTextItem { Text = p.Name, Id = p.Id })
                                     .Take(maxResults));
        }
    }

Last edited May 13, 2011 at 7:16 AM by o, version 3

Comments

No comments yet.