Click here to Skip to main content
15,880,725 members
Articles / Programming Languages / Javascript
Tip/Trick

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 88.8K   28   8
A simple example of how to use jQuery Autocomplete to make an AJAX call to WebAPI in an MVC4 application.
  • 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:

XML
<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: 

C#
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: 

C#
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:

C#
[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:

C#
@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:

XML
<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:

XML
@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)


Written By
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 3:07
Member 1133644610-Apr-15 3:07 
Questioncould not get it to display Pin
jsoh12322-Dec-14 18:03
jsoh12322-Dec-14 18:03 
QuestionWorks great. Thanks. Pin
JoshYates19809-Apr-14 3:29
professionalJoshYates19809-Apr-14 3:29 
AnswerRe: Works great. Thanks. Pin
luivis79-Apr-14 13:06
luivis79-Apr-14 13:06 
QuestionWebApi Controller method Pin
Kris Adams TV28-Oct-13 5:01
Kris Adams TV28-Oct-13 5:01 
AnswerRe: WebApi Controller method Pin
luivis728-Oct-13 5:18
luivis728-Oct-13 5:18 
GeneralMy vote of 3 Pin
damian-piatkowski19-Aug-13 10:07
damian-piatkowski19-Aug-13 10: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.