skip to the main content area of this page

Create an autocomplete textbox using jQueryUI

Posted on Tuesday, November 15, 2011 at 6:17 PM in ASP.NET 0 comments

There are a number of jQuery autocomplete plugins available. When creating this blogging application I realized I wanted one autocomplete textbox for Categories and one for Tags when writing a new post. You can see the autocomplete functionality illustrated below.

Tag Autocomplete

The one most folks used was the plugin from bassisstance.de. However this plugin has been deprecated in favor of the autcomplete solution available in jQueryUI. jQueryUI is included when you create a new MVC 3 internet application. It is also a trivial matter to add jQueryUI to an existing application. If you don't have the core jquery file and jQueryUI in your MVC 3 application, you can grab the latest jQuery core file which is at 1.7 from jquery.com. Over at jQueryUI, you can either download a custom version of jQueryUI with only the bits you want or you can just get the entire jQueryUI library. For the autocomplete textbox, you will need at the minimum Core, Widget, Position and Autocomplete. After you download the jQueryUI package, you will find a css file with the styles needed for the autocomplete textbox. After the files are downloaded, you will need to copy them into your scripts and css folders.

After copying them into the appropriate folders, open the vbhtml or cshtml file that will have the autocomplete textbox. Add the scripts and css file to the view:

<link href="@Url.Content("~/YourCssFolder/jquery-ui-1.8.16.custom.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/YourScriptFolder/jquery-1.4.4.js")" type="text/javascript"></script>
<script src="@Url.Content("~/YourScriptFolder/jquery-ui.min.js")" type="text/javascript"></script>

With some jquery in the vb/cshtml file, you can bind the autocomplete widget to the textbox. Add another script tag and the following jquery:

$("#TextboxId").autocomplete({
        source: 'Controller/Action', 
        minLength: 1,            
        select: function (event, ui) {
            if (ui.item) {
            $("#TextboxId").val(ui.item.value);
            }
            }

});

In the code above, the datasource is a controller and the specified action. The minLength property determines how many letters it takes to trigger the autocomplete functionality.  Finally, we code the autcomplete select function's to set the selected value as the value of the textbox.

Next, we will look at the action.

Public Function GetCategories(ByVal term As String) As JsonResult
            Dim cat = ctx.Categories.Where(Function(x) x.CategoryName.ToLower.StartsWith(term.ToLower)).OrderBy(Function(c) c.CategoryName).Select(Function(y) y.CategoryName)
            Return Json(cat, JsonRequestBehavior.AllowGet)
End Function

I am using EF for data access. The action gets categories that starts with the the first letter typed into the textbox. I use ToLower to make the search case insensitive - so I can type either g or G and still get back General as a choice for example. The categories are sorted alphabetically which makes the final display a little neater. The result is then returned as JSON. Ideally you should place this function in your repository and the controller calls the respository.  When writing this blog application, I placed all my data access code in a repository class.

The view for the demo is very simple; it just has a textbox.

<!DOCTYPE html>
<html>
<head runat="server">
    <title>Categories</title>
    <script src="@Url.Content("~/ScriptsFolder/jquery-1.6.2.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/ScriptsFolder/jquery-ui.min.js")" type="text/javascript"></script>
    <link href="@Url.Content("~/ContentFolder/jquery-ui-1.8.16.custom.css")" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#Category").autocomplete({
            source: 'Ajax/GetCategories',
            minLength: 1,
            select: function (event, ui) {
                if (ui.item) {
                    $("#Category").val(ui.item.value);
                }
            }

        });
    });
    </script>
</head>
<body>  
    @Using Html.BeginForm
          @<p>Enter the first of a category such as G for General, P for photography. </p>
Category:@Html.TextBox("Category")
    End Using     
</body>
</html>

I recommend using either Firefox or Chrome to test the page since with either browser you can check the Ajax response. This is huge help in debugging when it does not work right the first time as it did for me. 

One gotcha is the following. When viewing the response in Firefox/Firebug, you may get the message:

A public action method xxx was not found on controller xxxxx.

If this occurs, you need to add a route for the controller and action in your global.asax file. Then the Ajax response should work as expected.

The demo page is here. Type a letter, for example A, and you'll see ASP.NET appear as a choice.

Tags: MVC jQuery

Shout it Kick It on DotNetKicks.com

Comments:

No comments have been made for this post. Be the first to leave a comment! Reply