ASP.NET MVC Implement Autocomplete TextBox using jQuery




In this tutorial, I am going to explain you how to implement autocomplete textbox in asp.net mvc using jquery ajax. We will be using Visual Studio 2013.

Creating ASP.NET MVC Empty Application

Now the next step is to create ASP.NET MVC empty application as shown below.
Go to File → New → Project. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 empty folder structure

Adding Models

Go to Models folder and add new class file Country.cs. Now replace all code with below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class Country
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}

Adding Controller

Next step is to add controller to application. Go to controller folder and add new empty controller named as Home controller. Replace all code with below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult Index(string Prefix)
    {
        List<Country> countryList = new List<Country>() 
        { 
            new Country {ID=1,Name="India" }, 
            new Country {ID=2,Name="USA" }, 
            new Country {ID=3,Name="UK" }, 
            new Country {ID=4,Name="Austraila" }, 
            new Country {ID=5,Name="Nepal" },
            new Country {ID=5,Name="Afghanistan" },
            new Country {ID=5,Name="Albania" },
            new Country {ID=5,Name="Andorra" },
            new Country {ID=5,Name="Austria" }
        };

        var obj = from country in countryList
                    where country.Name.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase) // use StartsWith function
                    // where country.Name.ToLower().Contains(Prefix.ToLower()) // use contains function
                    select new { country.Name };

        return Json(obj, JsonRequestBehavior.AllowGet);
    }
}
}

Adding View

Now, right click on home controller index action method, add new view and name Index. Select Empty template and uncheck Use layout page and click on Add as shown below.

Addling index view

Now go to Views / Home folder, open Index.cshtml file and replace all code with below code. Here first 3 files are required files i.e jquery.js, jquery-ui.js, jquery-ui.css. And 4th file is bootstrap which is optional.

Index.cshtml Code:
@model WebApplication1.Models.Country

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js" type="text/javascript"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />

    <link href=" https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.css" rel="stylesheet" />

    <script type="text/javascript">
        $(document).ready( function () {
            $("#Name").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "/Home/Index",
                        type: "POST",
                        dataType: "json",
                        data: { Prefix: request.term },
                        success: function (data) {
                            response($.map(data, function (item) {
                                return { label: item.Name, value: item.ID };
                            }))

                        }
                    })
                },
                messages: {
                    noResults: "", results: ""
                }
            });
        })
    </script>

</head>
<body>
    @using (Html.BeginForm())
    {
        <div class="form-group" style="width:500px;margin-left:150px;">
            <table class="table">
                <tbody>
                    <tr>
                        @ Html.TextBoxFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                        @* @Html.TextBox("Name", null,new { @class = "form-control" }) *@
                    </tr>
                </tbody>
            </table>
        </div>
    }
</body>
</html>

Output can be seen as below as you type country name starts with 'AU'.

ASP.NET MVC Implement Autocomplete TextBox using jQuery


Share This


blog comments powered by Disqus