Click here to Skip to main content
15,116,815 members
Articles / Programming Languages / Javascript
Posted 19 Aug 2013


28 bookmarked

jQuery Autocomplete, MVC4, and WebAPI

Rate me:
Please Sign up or sign in to vote.
5.00/5 (13 votes)
19 Aug 2013CPOL2 min read
A simple example of how to use jQuery Autocomplete to make an AJAX call to WebAPI in an MVC4 application.
  • Download source code here


This article will describe how to implement jQuery Autocomplete with ASP.NET WebAPI. jQuery Autcomplete is party of the jQuery UI library of widgets and it allows one to easily transform a textbox into an autocomplete textbox by providing a data source for the autocomplete values. 


Some basic knowledge of MVC4, jQuery, and WebAPI is recommended before reading this article. This article will use SQL Server Compact Edition (which can be installed via NuGet), and Entity Framework which is already installed by default in MVC 4's internet template.

Using the code

Installing SQL Server CE

In the package manager console, go ahead and type in the following, to install SQL Server Compact Edition:

PM> Install-Package SqlServerCompact 

Now you can add the following to your connection strings in your web.config file:

    <add name="MyContext" connectionString="Data Source=|DataDirectory|data.sdf" 
               providerName="System.Data.SqlServerCe.4.0" />

Creating the Model 

We'll begin by creating a simple MVC4 application using the internet template. Now we'll create a new model inside the Models folder and a context: 

public class Product
    public int Id { get; set; }
    public string Description { get; set; }

public class MyContext : DbContext
    public DbSet<Product> Products { get; set; }

Adding the WebAPI Controller 

Now that we got the model created, we can go ahead and add the WebAPI controller that will be responsible for returning the data to the autocomplete search box: 

public class ProductApiController : ApiController
    public IEnumerable<Product> GetProducts(string query = "")
        using(var db = new MyContext())
            return String.IsNullOrEmpty(query) ? db.Products.ToList() : 
            db.Products.Where(p => p.Description.Contains(query)).ToList();

Adding the Product Controller 

We will need three simple methods in our MVC Product controller:

public ActionResult Search()
    return View();

public ActionResult Search(Product product)
    return RedirectToAction("Details", "Product", new { Id = product.Id });

public ActionResult Details(int Id)
    return View();

Adding the Views

We will need two views to handle the controller actions, our first view is where we are going to link up jQuery to turn our textbox into an autocomplete searchbox:

@using (Html.BeginForm())
    @Html.HiddenFor(m => m.Id)
    <input type="text" id="search" placeholder="Search for a product" required />
    <input type="submit" value="Go" id="submit" />

<script type="text/javascript">
    var url = '@Url.RouteUrl("DefaultApi", 
        new { httproute = "", controller = "ProductApi" })';
        source: function (request, response) {
                url: url,
                data: { query: request.term },
                dataType: 'json',
                type: 'GET',
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.Description,
                            value: item.Id
        select: function (event, ui) {
            return false;
        minLength: 1

We are  using three properties of the AutoComplete: source, select, and minLength. Source is going to be the AJAX call to our WebAPI controller in JSON format, we are then mapping the label to the description and the value to the ID. Setting the select property is going to set the search box text to the label and the value of the hidden input to the ID. minLength is optional and for demonstration purposes is 1.

We also need to make sure to reference the jQuery core and jQueryUI libraries. For simplicity, we can add the references directly to their libraries online:

<link rel="stylesheet" href="" />
<script src=""></script>
<script src=""></script>  

The final view is a simple details page where we can view the product we searched for:

@model AutoComplete.Models.Product


    <div class="display-label">
         @Html.DisplayNameFor(model => model.Description)
    <div class="display-field">
        @Html.DisplayFor(model => model.Description)
    @Html.ActionLink("Back to search", "Search")


That's it, now we have a fully working autocomplete search box. It might seem like a lot, but hopefully it helps, as I have not been able to find any tutorials online that go full circle and demonstrate the usage of jQuery autocomplete with external data sources and redirecting to other pages.

Let me know if you have questions, hope it helps!

  • Download source code here


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer
United States United States
Bachelor in Computer Engineering. When I'm not programming at work, I'm working on my personal project(s), and reading articles about new technologies, especially .NET and web development.

Comments and Discussions

QuestionAutocomplate Dont Work Pin
Member 1133644610-Apr-15 4:07
MemberMember 1133644610-Apr-15 4:07 
Questioncould not get it to display Pin
jsoh12322-Dec-14 19:03
Memberjsoh12322-Dec-14 19:03 
QuestionWorks great. Thanks. Pin
JoshYates19809-Apr-14 4:29
professionalJoshYates19809-Apr-14 4:29 
AnswerRe: Works great. Thanks. Pin
luivis79-Apr-14 14:06
Memberluivis79-Apr-14 14:06 
QuestionWebApi Controller method Pin
Kris Adams TV28-Oct-13 6:01
MemberKris Adams TV28-Oct-13 6:01 
AnswerRe: WebApi Controller method Pin
luivis728-Oct-13 6:18
Memberluivis728-Oct-13 6:18 
GeneralMy vote of 3 Pin
damian-piatkowski19-Aug-13 11:07
Memberdamian-piatkowski19-Aug-13 11:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.