.NET Development Examined

jQuery Autocomplete with MVC Part 1

Monday, April 4, 2011

 jQuery is a fantastic way to interject dynamic content and actions into your web pages. MVC is Microsoft’s cutting edge data driven web technology. More and more we are seeing the two technologies 'married' together to give the user a very interactive, high scalable experience. Recently I had an inventory system that I wanted to allow the customer to input the product id, or partial product name and quickly navigate to the details of that product. In another area I wanted to allow the population of a form based on previous data entry, so again a lookup of data was desired. The autocomplete feature of jQuery proved to be the tool for both of these tasks.

I found a couple of post by Mr. James that gave me a great head start.

For this exercise I created a simple 3 page MVC project that used the Northwind Customers table. I also elected to use the EntityFramework to manage the connection to the database.

Step 1 – Setting Up the Base Project

Start a new MVC 3 Web Application; I used the Empty Site to minimize the clutter.  Add a new Controller (I called mine HomeController) and create your initial Index view to make sure your project is running.

Add a new ASP.NET App_Data folder and add an Existing Item of the Northwind database (be sure to grab the index file as well).

Fire up NuGet and install the EntityFramework (see ScottGu’s blog for a good post on version 4.1).
Add your connection string:

<add name="NorthWindEntities" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|NORTHWND.MDF;User Instance=true" providerName="System.Data.SqlClient" />

In the Models folder add two classes to establish your EntityFramework connection to the Northwind database:


using System.Data.Entity; namespace jQueryAutoComplete.Models { public class NorthWindEntities : DbContext { public DbSet Customers { get; set; } } }


using System.ComponentModel.DataAnnotations; namespace jQueryAutoComplete.Models { public class Customers { [Key] public string CustomerID { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string ContactTitle { get; set; } public string Address { get; set; } public string City { get; set; } public string Region { get; set; } public string PostalCode { get; set; } public string Country { get; set; } public string Phone { get; set; } public string Fax { get; set; } } }

Step 2 – “Install” jQuery

Now that we have the project structured and connected to some data we can focus our attention to the task at hand, jQuery Autocomplete…

Head on over to http://www.jQueryUi.com and download the latest package. You can select what you want to include in your package, but be sure to include the Autocomplete for this exercise. The download at the end of the article will include all Interactions, Widgets, and Effects for v 1.8.11. Extract the \css and \js folders to a temporary place.

Back in Visual Studio right click on the \Scripts folder and select the Add\Existing Item, browse to your temp location and grab the jquery-ui-1.8.11.custom.min.js and the jquery-1.5.1.min.js files.

In the \Content folder create a new folder to hold your theme and images, mine was called humanity. Add all the files located in the temporary \css folder. While the autocomplete does not use them, make sure you grab the images folder if you are going to use any other jQuery Ui features.

Back in the \Views\Shared folder open the _Layout.cshtml file and update it with the newer version of the jQuery, and add a reference to the custom jQuery Ui and it’s css stylesheet.

Step 3 – Hook UP the Autocomplete

The autocomplete feature requires three basic components; a textbox to enter text, some javascript to trigger an Ajax call, and a source for your data. The text box is simple, just add a simple text input to your page, be sure to note the id given, you will need to reference it later:

Find:<input type="text" id="find-list" />

The javascript is a little more involved:

<script type="text/javascript" language="javascript"> $(function () { $("#find-list").autocomplete({ source: function (request, response) { $.ajax({ url: "/home/Lookup", type: "POST", dataType: "json", data: { searchText: request.term, maxResults: 10 }, success: function (data) { response($.map(data, function (item) { return { label: item.ContactName + '(' + item.CompanyName + ')', value: item.ContactName, id: item.CustomerID } })) } }) }, select: function (event, ui) { alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id) : "Nothing selected, input was " + this.value); } }); }); </script>

Let’s look at it for a moment.  We can see by the line $("#find-list").autocomplete
That we are hooking up the jQuery autocomplete the element with the id “find-list” (if you called your text input something else be sure to adjust this). We are then firing an Ajax call to the controller listed in the url: "/home/Lookup" line.  We are telling jQuery to to a POST action with a data type of JSON, and passing two variables, searchText and maxResults.

Upon a successful call we parse the data an assign it to three variables, label, value, and id.  The label is what jQuery will use to build the drop down list of results, and the value is entered into the text input. We are declaring a third varable id, which we will use to identify who was selected.

The select function fires when the user actually selects an item in the list, either by pressing the enter key, or selecting with a mouse. In this example it simply displays a dialogue box showing the selected customers name, company, and id.

Before we can run our application we need to generate the data source for display. In your Home controller add a new function called LookUp:

[HttpPost] public JsonResult Lookup(string searchText, int maxResults) { var result = (from c in nw.Customers where (c.CompanyName.Contains(searchText) || c.ContactName.Contains(searchText)) orderby c.ContactName select new { c.CompanyName, c.ContactName, c.CustomerID }) .Distinct().Take(maxResults).ToList(); return Json(result); }


Notice that we are returning a Json result so that jQuery can easily digest the search results. We are also searching both the contact and company name, so the user can type in whatever they know. We are returning the unique instance of each CompanName, ContactName, and ContactID for use in our javascript.

Running the project now should allow you to type in phrase in the Find textbox and generate a drop down list based on your search criteria. So far so good, but we want to do something more useful than displaying a message with the customer’s details.

For my purpose I had two different tasks, one was to populate a form, the other was to navigate to the details of the selected person/company.

These are covered in Part 2 of this series.


Add Comment