jQuery UI has an AutoComplete widget. The AutoComplete widget is quite nice and straight forward to use. In this post, I will show you how to use jQuery AutoComplete widget to consolidate AutoComplete function in ASP.NET MVC application.

Step 1

The first step is to add the jQuery scripts and styles. With ASP.NET MVC, the following code does the work:

@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/jquery")   
@Scripts.Render("~/bundles/jqueryui")

Step 2

Using the AutoComplete widget is also simple. You will have to add a textbox and attach the AutoComplete widget to the textbox. The only parameter that is required for the widget to function is source. For this example, we will get the data for the AutoComplete functionality from a MVC action method.

$(document).ready(function () {
    $('#tags').autocomplete(
        {
            source: '@Url.Action("TagSearch", "Home")'
    });
})

In the above code, the textbox with id=tags is attached with the AutoComplete widget. The source points to the URL of TagSearch action in the HomeController: /Home/TagSearch. The HTML of the textbox is below:

<input type="text" id="tags" />


Step 3

When the user types some text in the textbox, the action method (TagSearch) is called with a parameter in the request body. The parameter name is term. So, your action method should have the following signature:

public ActionResult TagSearch(string term)
{
    // Get Tags from database
    string[] tags = { "ASP.NET", "WebForms",
                    "MVC", "jQuery", "ActionResult",
                    "MangoDB", "Java", "Windows" };
    return this.Json(tags.Where(t => t.StartsWith(term)),
                    JsonRequestBehavior.AllowGet);
}

Now, the AutoComplete functionality is complete!

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.