Click here to Skip to main content
Click here to Skip to main content

jQuery Autocomplete, MVC4, and WebAPI

By , 19 Aug 2013
Rate this:
Please Sign up or sign in to vote.
  • Download source code here

Introduction

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. 

Background

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:

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

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
{
    [HttpGet]
    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:

[HttpGet]
public ActionResult Search()
{
    return View();
}

[HttpPost]
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" })';
    $('#search').autocomplete({
        source: function (request, response) {
            $.ajax({
                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) {
            $('#search').val(ui.item.label);
            $('#Id').val(ui.item.value);
            return false;
        },
        minLength: 1
    });
</script>  

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="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>  

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

@model AutoComplete.Models.Product

<fieldset>
    <legend>Product</legend>

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

Remarks

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

License

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

About the Author

luivis7
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

 
QuestionWorks great. Thanks. PinprofessionalJoshYates19809-Apr-14 3:29 
AnswerRe: Works great. Thanks. Pinmemberluivis79-Apr-14 13:06 
QuestionWebApi Controller method Pinmemberkris86091128-Oct-13 5:01 
AnswerRe: WebApi Controller method Pinmemberluivis728-Oct-13 5:18 
GeneralMy vote of 3 Pinmemberdamian-piatkowski19-Aug-13 10:07 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140421.2 | Last Updated 19 Aug 2013
Article Copyright 2013 by luivis7
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid