ASP.NET MVC, Web Api, Windows Azure, Microsoft SharePoint, WCF, WPF, Windows Phone 8, AngularJS, jQuery, HTML, CSS, JavaScript, AJAX, JSON, Twitter Bootstrap

jQuery UI AutoComplete Widget with ASP.NET MVC

10 comments

In this post I am showing you how to use jQuery UI Autocomplete widget with ASP.NET MVC. The Autocomplete widget provides suggestions when you type some text into the text field. This is very useful when you provide search box to find data, so lets start using it in Fresh ASP.NET MVC website.

Overview

From the jQuery UI website, Autocomplete, when added to an input field, enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

By giving an Autocomplete field focus or entering something into it, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

Autocomplete can be customized to work with various data sources, by just specifying the source option. A data source can be:

  • an Array with local data
  • a String, specifying a URL which returns Json formatted data
  • a Callback


What you will need?

To use jQuery UI widgets you will need jQuery UI library, you can download the latest version from here. Please make sure that you select the Autocomplete checkbox in the widgets section while downloading.
After unzip, the library folder structure looks something like this:

jQuery UI files

From here we are interested in CSS and JS Folder. CSS folder contains the theme files [images and stylesheet] which you selected while downloading, in JS folder you will find JavaScript files which are required to work with jQuery UI.

Setting up project

I am assuming that you have Visual Studio 2010 Express or higher installed along with SQL Server 2008 Express or higher. I am using Visual Web Developer 2010 Express and SQL Server 2008 R2 Express on my machine both are freely available from Microsoft. I like Microsoft products very much.

Open Visual Web Developer 2010 Express from start menu and create new ASP.NET MVC 2 Empty Web Application project from the installed templates, you now have a working project.

Now add jQuery UI library to the newly created project.

Add images folder and jquery-ui-1.8.2.custom.css file from the CSS folder to the Content folder in the project then add both JavaScript files from JS folder to the Scripts folder.

Your solution explorer window may look like this:

Solution Explorer

In this MVC application I’ll use AdventureWorks LT 2008 R2 database to show data in jQuery UI Autocomplete widget. To work with the database I’m also adding ADO.NET Entity Data Model [edmx] file in the Models folder, I am adding only Customer table from the AdventureWorks LT 2008 R2 database.

Lets add our Data Model in the project, right click on the Models folder and select add new item, select ADO.NET Entity Data Model from the list of items in the Add New Item dialog and name it AdventureWorksDB.edmx. Follow the wizard and add connection to the AdventureWorks LT 2008 R2 Database or any other database that you have on your  machine and add table that you want to work with, but you have to change some code according what you have selected.

If you done exactly as described then we have our Data Model ready to work in the Models folder.
Now add Controller in the project, just right click on the Controller folder and click Add Controller, name the controller as you want I name it HomeController:

Add Controller

Now we have to add HomeController’s Action method which returns Json formatted data of Customers Object from the AdventureWorks database.

Here is the Action Method which is called by the Autocomplete widget and returns Json formatted data.

public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}

public JsonResult GetCustomers(string term)
{
AdventureWorksEntities db = new AdventureWorksEntities();
var customers = from cust in db.Customers.Where(c => c.LastName.StartsWith(term))
select cust.LastName;
customers = customers.Distinct();
return Json(customers, JsonRequestBehavior.AllowGet);
}
}

In the above code for the HomeController there are two Action methods, Index() which is created by default and GetCustomers(string term) which is used to get Json formatted data. In the GetCustomers(string term) you see we passed parameter “term” of string type, which is passed as a Request variable from the Autocomplete widget and is used to get data based on it.

Before working with the Entity Data Model we first need to add a using C# statement in the HomeController to get reference to the Models just like that:

using YOURPROJECTNAME.Models;

Move to the GetCustomers(string term) Action method, I declared a variable db of type AdventureWorksEntities which have all our Data Objects programmed in it by the Entity Framework, I then defined a variable customers and shape the required data by using LINQ to Entities, remove duplicate entries by calling Distinct() Extension method and finally return customers as a Json.

Ok, we now have our Controller ready for the Autocomplete widget, finally we have to add a View for the Index() Action method, to add a view simply right click anywhere in the HomeController’s Index() Action method and click Add View context menu item this is the easiest way to add View. Follow the options as shown in the image below for Add View.

Add View

I didn’t add any Master View page to the project yet that’s why I didn’t checked Select master page checkbox, if you have one added already then you can check it.

Visual Web Developer adds Index View as Index.aspx in the Views/Home folder and opened it for editing. In the Index.aspx view page add the following code in the head section which are required to add Autocomplete suggestion feature to the text fields.

<link href="../../Content/jquery-ui-1.8.2.custom.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script>
After adding above references add the following HTML code in the body section which adds a label and text input control which acts as a Autocomplete widget.
<label for="customers">Find:</label>
<input type="text" id="customers" />
Finally add the following javascript code in the head section to bind the Autocomplete widget to the text input field.
<script type="text/javascript">
$(function () {
$('#customers').autocomplete({
source: '<%= Url.Action("GetCustomers") %>',
minLength: 2
});
});
</script>

We are done here with Autocomplete widget, now build and run the application by pressing F5. If all goes well then you are presented with application running in the default internet browser, to test Autocomplete widget just type two or more letters in the input field and the results will show instantly. see the screenshot below:

Autocomplete Output

I hope you have successfully implement Autocomplete widget as described above. jQuery UI Autocomplete widget has a few options to set as desired, you can have a look on it by going here.

Hope this works!

10 comments :

  1.  It worked. Thanks for informative article.

    ReplyDelete
  2. how to pass value to the controller?My program I need to send 2 values but the source of autocomplete field here does not contain any parameter.
    Please help.

    ReplyDelete
  3. Hi Amit,

    What do you want to do? Please briefly describe me, so that I could help you.

    ReplyDelete
  4. When you select a customer how do you wire it to go to another action say "Edit" and pass it an id?

    Thanks,

    -Samah

    ReplyDelete
  5. Hello Samah,

    All you need to use select event of the autocomplete, please look it here: http://goo.gl/UBlmX

    here is the example:

    $( ".selector" ).autocomplete({
    select: function(event, ui) { ... }
    });

    Hope this helps!
    -Shahnawaz

    ReplyDelete
  6. Best example for ASP.Net MVC I have seen. Thanks.

    ReplyDelete
  7. Nothing works. no error message not response. doesnt work

    ReplyDelete
  8. Nice One i loved It. But my Main problem is that when i select Name the Id should be stored in database is there any way

    ReplyDelete
  9. Great! I would recommend to check shield ui combobox control with autocomplete
    https://demos.shieldui.com/mvc/combobox/auto-complete

    ReplyDelete

Thanks for posting valuable comments, your comments will be reviewed before publishing.