AutoComplete TextBox with ASP.NET MVC and jQuery

jQuery UI has an AutoComplete widget. The widget is quite nice and straight forward to use. In this post, we will see how to integrate the widget with an ASP.NET MVC application.

Bundling

The first step is to add the jQuery scripts and styles into bundles. There is a script bundle for jQuery. And another script bundle for jQuery UI. Not all pages use the jQuery UI. So, having a separate bundle helps.

@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/jquery")    
@Scripts.Render("~/bundles/jqueryui")

Client side

Add a TextBox to the page.

<input type="text" id="tags" />

Attach the AutoComplete widget to the TextBox. Provide the source parameter. When user enters text in the TextBox, we get suggestions from a MVC action method. The action method is TagSearch in the HomeController.

$(document).ready(function () {
    $('#tags').autocomplete({
            source: '@Url.Action("TagSearch", "Home")'
    });
})

Server side

The widget calls TagSearch method with a parameter in the request body. The parameter name is term. So, our action method should have the following signature.

public ActionResult TagSearch(string term)
{
    // Get Tags from database
    string[] tags = { "ASP.NET", "WebForms", 
                    "MVC", "jQuery", "ActionResult", 
                    "MangoDB", "Java", "Windows" };
    return this.Json(tags.Where(t => t.StartsWith(term)), 
                    JsonRequestBehavior.AllowGet);
}

Usually, the action method gets filtered data from a database. All the suggestions are sent back as JSON to the widget. The widget shows it beneath the TextBox. There are several options to adjust the style of the widget.

Related Posts

Leave a Reply

Your email address will not be published.