Global AutoCompleBox For MVC

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:

  1. $(document).ready(function () {   
  2.     $('*[data-autocomplete-url]')   
  3.     .each(function () {   
  4.         $(this).autocomplete({   
  5.             source: $(this).data("autocomplete-url")   
  6.         });   
  7.     });   
  8. }); 

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:

  1. public static class AutocompleteHelpers  
  2. {  
  3.     public static MvcHtmlString AutocompleteFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, string actionName, string controllerName)  
  4.     {  
  5.         string autocompleteUrl = UrlHelper.GenerateUrl(null, actionName, controllerName,null,html.RouteCollection,html.ViewContext.RequestContext,includeImplicitMvcValues: true);  
  6.         return html.TextBoxFor(expression, new { data_autocomplete_url = autocompleteUrl });  
  7.     }  

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:

  1. public ActionResult Autocomplete(string term)  
  2. {  
  3.     var getValues = MyAutoCompleteCollection.Where(item => item.ToLower().StartsWith(term.ToLower())).ToList();  
  4.     // Return the result set as JSON  
  5.     return Json(getValues, JsonRequestBehavior.AllowGet);  

The View

Everything is ready now. So we can specify our view and use the helper as follows:

  1. @Html.LabelFor(m=>m.YourPropertyName)   
  2. @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.


Similar Articles