Friday, December 18, 2015

Asp.net MVC: Autocomplete textbox using jquery

In this article I am going to explain how to create the autocomplete textbox in asp.net MVC using Jquery.


Description:
I have a table Tb_Movie. I want to create autocomplete textbox to filter the records based on movie name. Means when we start typing in textbox, suggestion (matching) should appear.

Implementation:
Add an empty controller to project. Import the model namespace to controller:
using MvcApplication3.Models;

Create the object of entity connectionstring :
DemoEntities db = new DemoEntities();

Create a Json method in controller that will accept the search parameter and display the matching record.
[HttpPost]
        public JsonResult FindMovieName(string prefixText)
        {
            var moviename = from x in db.Tb_Movie
                                where x.Name.StartsWith(prefixText)
                                select new
                                {
                                    name = x.Name
                                };
                var result = Json(moviename.Take(5).ToList());
                return result;          
        }

Complete code of Controller (AutocompleteController.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication3.Models;

namespace MvcApplication3.Controllers
{
    public class AutocompleteController : Controller
    {
        //
        // GET: /Autocomplete/
        DemoEntities db = new DemoEntities();
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult FindMovieName(string prefixText)
        {
            var moviename = from x in db.Tb_Movie
                                where x.Name.StartsWith(prefixText)
                                select new
                                {
                                    name = x.Name
                                };
                var result = Json(moviename.Take(5).ToList());
                return result;          
        }
    }
}

Now add a view. To add a view right click on Index and choose the add view option.
@using (Html.BeginForm())
{
    <p>
       <strong>Search the Movie</strong>  :  @Html.TextBox("SearchString")
    </p>
}

Add the below given script to view:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css">
    <script>
        $(document).ready(function () {
            $("#SearchString").autocomplete({
                autoFocus: true,
                source: function (request, response) {
                    $.ajax({
                        url: "/Autocomplete/FindMovieName",
                        data: "{ 'prefixText': '" + request.term + "' }",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item.name,
                                    value: item.name
                                }
                            }))
                        },
                        messages: {
                            noResults: "", results: ""
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                minLength: 1,
            });
        });
    </script>

Complete Markup of view:
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Autocomplete Tutorial</title>
</head>
<body>
   
        @using (Html.BeginForm())
{
    <p>
       <strong>Search the Movie</strong>  :  @Html.TextBox("SearchString")
    </p>
}
  
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css">
    <script>
        $(document).ready(function () {
            $("#SearchString").autocomplete({
                autoFocus: true,
                source: function (request, response) {
                    $.ajax({
                        url: "/Autocomplete/FindMovieName",
                        data: "{ 'prefixText': '" + request.term + "' }",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item.name,
                                    value: item.name
                                }
                            }))
                        },
                        messages: {
                            noResults: "", results: ""
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                minLength: 1,
            });
        });
    </script>
</body>
</html>

Now build, run the project and test it.

 DEMO:
Asp.net MVC: Autocomplete textbox using jquery
     In this article we have learn how to create autocomplete textbox using Jquery in asp.net. I hope you enjoyed this article. Please post you comment, query and feedback about this article. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.  

No comments:

Post a Comment