Introduction
This article provides an overview of how to create a HTML helper to enable the “Auto complete” feature of a TextBox so that you can use it globally. Unfortunately I can't share the complete source code since it is tightly coupled with our project. But you will definitely get a basic and useful idea of how to implement it so that you can use it in your project.
Prerequisites
You need to have the jQuery UI script file and CSS file. You can get it through the web.
The Script
We can create a separate script file that adds auto complete behaviors for these elements as in the following:
- $(document).ready(function () {
- $('*[data-autocomplete-url]')
- .each(function () {
- $(this).autocomplete({
- source: $(this).data("autocomplete-url")
- });
- });
- });
This script identifies any elements with the data-autocomplete-url attribute. Then it calls autocomplete(), using the value of the data-autocomplete-url attribute as the data source.
The Helper
We know the HTML Helpers are all extension methods, so we can definitely define our own AutoComplete extension for it. It will just obtain the URL and then call the TextBoxFor:
- public static class AutocompleteHelpers
- {
- public static MvcHtmlString AutocompleteFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, string actionName, string controllerName)
- {
- string autocompleteUrl = UrlHelper.GenerateUrl(null, actionName, controllerName,null,html.RouteCollection,html.ViewContext.RequestContext,includeImplicitMvcValues: true);
- return html.TextBoxFor(expression, new { data_autocomplete_url = autocompleteUrl });
- }
- }
There is one extra piece of magic that ASP.NET MVC 3 added: underscores in property names are converted to dashes in the attribute names. In other words, a property name of “data_autocomplete_url” results in an attribute name of “data-autocomplete-url”.
The Controller
The controller is as simple as anything else. For project use, populate the collection from your DbSet Model class. For our example I hope this is enough to understand:
- public ActionResult Autocomplete(string term)
- {
- var getValues = MyAutoCompleteCollection.Where(item => item.ToLower().StartsWith(term.ToLower())).ToList();
-
- return Json(getValues, JsonRequestBehavior.AllowGet);
- }
The View
Everything is ready now. So we can specify our view and use the helper as follows:
- @Html.LabelFor(m=>m.YourPropertyName)
- @Html.AutocompleteFor(m=>m.YourPropertyName, "Autocomplete", "Home")
Now you are ready to extend this feature and develop your own custom AutoCompleteBox for MVC Razor. I hope this helps.