Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

jQuery Autocomplete, MVC4, and WebAPI

0.00/5 (No votes)
19 Aug 2013 1  
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:

<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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here