Home > ASP.NET, MVC, Uncategorized > How to use jQuery autocomplete with MVC

How to use jQuery autocomplete with MVC

Gone are the days of hand coding AJAX to get auto complete textboxes (a.k.a. incremental search).  jQuery’s Autocomplete widget does all the heavy lifting for you.

Want to know how to use it with an ASP.NET MVC app?  Microsoft has documented this step-by-step on their asp.net site.  The article shows how to use the widget two ways: 1) with items hard-coded on the page, and 2) with items retrieved from a call to the server (controller action).

To give you a leg up I’ll share my experience.

1. When setting the Source to point to the URL of your action, I used the razor markup instead of the angle bracket / percent side syntax.

So, the updated code looks like:

   source: '@Url.Action("List")', 
   select: function (event, ui) { 

2. The name of the parameter in the controller action must be “term” – any other name results in a null value being passed in.

3. Be sure that the property of the names you want to display is called “label”.

public ActionResult List(string term) { 
   var results = from m in _repository.Movies 
                 where m.Title.StartsWith(term) 
                 select new { label = m.Title, id = m.Id }; 
   return Json(results.ToArray(), JsonRequestBehavior.AllowGet); 

4. To get the right visual look you need to include some stylesheets:

   <link href="@Url.Content("~/Content/themes/base/jquery.ui.base.css")"
      rel="stylesheet" type="text/css" />
   <link href="@Url.Content("~/Content/themes/base/jquery.ui.core.css")"
      rel="stylesheet" type="text/css" />
   <link href="@Url.Content("~/Content/themes/base/jquery.ui.theme.css")"
      rel="stylesheet" type="text/css" />


  1. sathya
    January 26, 2013 at 7:02 am

    really very good blog….i struggle a lot for this…thanks for ur code…..

  2. sathya
    January 26, 2013 at 7:02 am

    Its working for me:)…thanks a lot

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: