Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

jQuery Autocomplete in MVC 3: Different Approaches and Customizations

5.00/5 (10 votes)
27 Nov 2013CPOL2 min read 42.1K  
Autocomplete feature of jQuery in a MVC 3 application.

Introduction

This article will describe how to implement the autocomplete feature from scratch in a .NET MVC application using jQuery.

Background

Basic knowledge of jQuery, and MVC is what is expected from a reader.  

Using the code

There are three sections here . The first two sections describe different ways of using the autocomplete feature and the third section describes how you can customize the display. Let's begin.

Please include the following scripts in your solution and add the reference in _layout.cshtml.

XML
<link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" 
            rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>

Note: Please do not change the order in which the .js files are referenced because if jquery-ui-1.8.11.min.js is used before jquery-1.5.1.min.js then some of the features will not be initialized in ui.js and may not perform correctly. So just follow the order.

Section 1:

In this section we will see how to use autocomplete in the simplest way.

Step 1: Prepare a list of data which needs to be shown in the textbox on typing any word.

In an ideal project this data needs to come from a typical database table,but here I am just building in the list in the controller itself as getting the data is out of the scope of this discussion.

C#
public JsonResult Autocomplete(string term)
{
    var items = new[] { "Apple", "Pear", 
           "Banana", "Pineapple", "Peach" };
    var filteredItems = items.Where(
         item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
        );
    return Json(filteredItems, JsonRequestBehavior.AllowGet);
}

Step 2: In the Student.cshtml file, place the following code:

C#
@
using(Html.BeginForm())
{
    <label for="fruitvalue">Select the fruit:</label>
    <input type="text" id="fruitvalue" name="fruitvalue"/>
    <input type="button" id="button1" />
}

Step 3: Add the following jQuery code in Student.cshtml.

JavaScript
<script type="text/javascript">
    $(document).ready(
function () {
        $( '#fruitvalue').autocomplete({
            source: 
'@Url.Action("Autocomplete")'
        });
    });
</script>

In the source, you can specify the controller and action where the list of objects are being returned.

Note:

public JsonResult Autocomplete(string term)

Make sure that term is the name of the parameter for the method, because request.term is a variable inside Autocomplete.

That's it. The list is populated in the textbox whenever the user types the text in the textbox.

Step 4: To test the value which is bound to the textbox, place the following code on button click:

JavaScript
$(
'#button1').click(function () {
var a = $('#fruitvalue').val();
            alert(a);
        });

Section 2:

Suppose you have a requirement like, the display list is "Name" and you want to bind the "Id"s for them correspondingly.

How do we proceed? Let's tackle this requirement as:

Step 1: Let's build the model first:

C#
public class Fruit
{
    public int FruitId { get; set; }
    public string Description { get; set; }
}

Step 2:

I have a view DemoPurpose.cshtml, place the following code in it:

JavaScript
@model HomeProductions.Models.
 Fruit
@
using (Html.BeginForm())
{
    @Html.HiddenFor(m => m.FruitId, 
    new {id="FruitId" })
    <input type="text" id="search"/>
    <input type="button" value="Go" id="submit" />
}

Step 3: We will bind the fruit name with the textbox and ID with the HiddenField FruitId.

JavaScript
<script type="text/javascript">
var url = '@Url.Action("DemoPurpose","Student")';
    $('#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,
        value1: item.FruitId
                        }
                    }));
                }
            })
        },
        select: 
function (event, ui) {
            $('#search').val(ui.item.label);
            $('#FruitId').val(ui.item.value1);
return false;
        },
        minLength: 1
    });

In the success part, you will notice I have used the name as "value1:item.FruitId".

Please don't declare as value:item.FruitId; other than the word "value", you can use anything else.

Because, when you scroll down the populated list, the IDs are displayed in the textbox if you declare it as value.

Section 3:

In this section we will concentrate on customizing the dropdown list's styles according to the client's needs.

Suppose you want to change the background color as orange:

You can navigate to the jquery.ui.autocomplete.css file present in /base and modify its Style property according to your needs.

CSS
ui-menu
    .ui-menu-item {
    background-color:Orange;
}

License

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