June 6, 2012

ASP.NET MVC Helper for Twitter Bootstrap's Typeahead plugin

Select lists make it easy for users to select a single item from a given range of options.

From a developers perspective, select lists are a pain in the ass. For simple text selections (let’s say the category of a news article), we need to provide a way for the user to maintain the list of categories. That means more forms, more code, more work.

Lately I’ve been using AutoComplete/Suggest components to provide a similar user experience. The key difference is that the list of options is generated from the user’s previous selections and they have the ability to add new options by simply typing some text.

Twitter Bootstrap includes the typeahead plugin for doing this. It’s not as comprehensive as jQuery’s AutoComplete plugin but for simple string lists it works well - so, I created an ASP.NET MVC Helper to make it easier to wire up:

    public static MvcHtmlString TypeaheadFor<TModel, TValue>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TValue>> expression, 
        IEnumerable<string> source, 
        int items = 8)
    {
        if (expression == null)
            throw new ArgumentNullException("expression");
		
        if (source == null)
            throw new ArgumentNullException("source");

        var jsonString = new JavaScriptSerializer().Serialize(source);

        return htmlHelper.TextBoxFor(
            expression, 
            new { 
                autocomplete = "off", 
                data_provide = "typeahead", 
                data_items = items, 
                data_source = jsonString 
            }
        );
    }

The Typeahead plugin reads the string array assigned to the input’s “data-source” attribute (it does not use an external service). In ASP.NET MVC this means the string array needs to be available within your view. The above helper serializes the input Enumerable<string> into a JSON string and then generates the text input.

Usage:

@Html.TypeaheadFor(model => model.Category, Model.Categories)

Result:

Twitter Typeahead Helper for ASP.NET MVC

© 2020 Ben Foster