Donate

ASP.NET MVC AutoComplete TextBox Using jQuery UI AutoComplete And Entity Framework

Hello and Good Evening!

This post demonstrates how to implement an AutoComplete TextBox in ASP.NET MVC using jQuery UI and Entity Framework. I've had applied this concept to some of my projects and has been helpful to the clients and users using the application. Enough of the chitchat and lets get started by simply following the steps below.
1. Create an ASP.NET MVC project and add NuGet packages for Bootstrap and jQuery UI.
2. Add an Entity Framework model to the project using one of Microsoft's sample database called AdventureWorks.
3. In your _Layout.cshtml, make sure to reference the jQuery library inside the head tag so that the jQuery UI will work as expected.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", null, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                </ul>
            </div>
        </div>
    </div>

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    <script src="~/Scripts/bootstrap.min.js"></script>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
</body>
</html>
4. In your HomeController class, create a view for the Index() method. We will add the JavaScript codes and make the necessary changes to the UI later. Next is to create two methods that return jSON data to the UI. The first method retrieves the country names from the database which will be populated for the dropdown in the AutoComplete feature. The second method will fetch the specific details of the country once the user has finished selecting the country triggered by the blur event.
using System;
using System.Linq;
using System.Web.Mvc;
using AutocompletejQueryUI.Models;

namespace AutocompletejQueryUI.Controllers
{
    public class HomeController : Controller
    {
        private static AdventureWorksEntities _context;

        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult GetCountries(string prefixText)
        {
            _context = new AdventureWorksEntities();

            var result = (from country in _context.CountryRegions.AsEnumerable()
                          where country.Name.ToLower().StartsWith(prefixText, StringComparison.OrdinalIgnoreCase)
                          select country.Name);

            return Json(result.ToArray(), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetCountryInfo(string Country)
        {
            _context = new AdventureWorksEntities();

            var result = (from country in _context.CountryRegions.AsEnumerable()
                          where country.Name.ToLower().Equals(Country.ToLower())
                          select new
                          {
                              country.Name,
                              country.CountryRegionCode
                          }).FirstOrDefault();

            if (result != null)
               return Json(result, JsonRequestBehavior.AllowGet);

            return Json(new EmptyResult(), JsonRequestBehavior.AllowGet);
      }
	}
}
5. In your Index.cshtml page, add script reference to jquery-ui.js and content reference to jquery-ui.css. Initialize the textbox with the autocomplete() function so that when a user types some character(s) into the textbox it will then send a POST request to the controller that will retrieve the countries that starts with the input characters and return those country records to be displayed below the textbox as a dropdown list control. If the user decides to leave the textbox, a blur event is triggered which then sends a POST to the controller passing in the user input as the parameter. Once a search criteria has been found, it will return the specific details as result. Otherwise, an empty result is returned.
@{
   ViewBag.Title = "Index";
   Layout = "~/Views/Shared/_Layout.cshtml";
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Edit</title>   
    <script src="~/Scripts/jquery-ui.js"></script>
    <link href="~/Content/jquery-ui.css" rel="stylesheet" />
    <script type="text/javascript">
        $(document).ready(function () {

            //autocomplete function
            $('[id$=Countries]').autocomplete({
                source: function (requst, response) {
                    var param = { prefixText: $('[id$=Countries]').val() };
                    $.ajax({
                        url: "Home/GetCountries",
                        data: JSON.stringify(param),
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            if (data != null) {
                                response($.map(data, function (item) {
                                    return {
                                        label: item,
                                        value: item
                                    }
                                }));
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                }
            });

            //capture selected country
            $('[id$=Countries]').blur(function (event) {
                var country = $(this).val();
                $.ajax({
                    url: "Home/GetCountryInfo",
                    data: '{ Country: "' + country + '"}',
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        if (data != null) {
                            if (data.Name !== undefined && data.CountryRegionCode !== undefined) {
                                var c_name = data.Name;
                                var c_code = data.CountryRegionCode;
                                alert('Code: ' + c_code + ', Name: ' + c_name);
                            }
                            else {
                                alert('Search yield empty result.');
                            }
                        }
                    },
                    error: function (a, b, c) {
                        alert("Error in Retrieving Record!");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <h2>Index</h2>
    @Html.TextBox("Countries")
</body>
</html>
Output
ASP.NET MVC AutoComplete TextBox Using  jQuery UI AutoComplete And Entity Framework
ASP.NET MVC AutoComplete TextBox Using  jQuery UI AutoComplete And Entity Framework

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.