Autocomplete | jQuery UI with ASP.NET MVC – Simple Example

In this postI will show you how to add an autocomplete  function to your ASP.NET MVC application. (Working with the version 3).


First of all get your add Search and Autocomplete action to your controller.

    public class HomeController : Controller
        public ActionResult Index()
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();

        public ActionResult Autocomplete()
            return View();

        public JsonResult Search(string term)
            List databaseusers = new List();
            databaseusers.Add("Darth Vader");
            databaseusers.Add("Boba Fett");
            databaseusers.Add("Luke Skywalker");
            databaseusers.Add("Han Solo");

            List users = databaseusers.FindAll(x => x.StartsWith(term,StringComparison.OrdinalIgnoreCase));

            return Json(users, JsonRequestBehavior.AllowGet);

We will create a list of random user names (where you normally would connect to the database).
Now hit F5 (start debugging) and browse this URL:


You shoud get this:

["Han Solo"]

It means that the backend is all setup and we are ready to create our search form!

Go to Shared\_Layout.chtml and add these lines to the

    	<link href="" rel="Stylesheet" type="text/css" /><script type="text/javascript" src=""></script><script type="text/javascript" src=""></script>

It should look like this:

    	<link href="@Url.Content(" rel="stylesheet" type="text/css" />
    	<link href="" rel="Stylesheet" type="text/css" /><script type="text/javascript" src=""></script><script type="text/javascript" src=""></script></pre>
<div class="page">
<div id="header">
<div id="title">
<h1>My MVC Application</h1>
<div id="logindisplay">@Html.Partial("_LogOnPartial")</div>
<div id="menucontainer">
<ul id="menu">
	<li>@Html.ActionLink("Home", "Index", "Home")</li>
	<li>@Html.ActionLink("Autocomplete", "Autocomplete", "Home")</li>
<div id="main">@RenderBody()</div>
<div id="footer"></div>

Go to Home/Autocomplete.cshtml and create an input text box:

    ViewBag.Title = "About Us";
     <input id="username-search" type="text" />

<script type="text/javascript">// <![CDATA[
        $(document).ready(function () {
                source: '@Url.Action("search","home")',
                minLength: 1

// ]]></script>

An that’s it!.

You can download a fully working example here:

You may also like...