Click here to Skip to main content
Click here to Skip to main content
Go to top

Auto Complete Using jQuery and ASP.NET MVC

, 19 Mar 2014
Rate this:
Please Sign up or sign in to vote.
This tip introduces Auto Complete Using jQuery and ASP.NET MVC.

Introduction

This tip introduces approaches to show suggestion while you type into the field(Text Box) in ASP.NET MVC project. It is possible by using jquery UI autocomplete method.

Using the Code

To start this task, you need jQuery and jQuery plugin libraries. You can download these from here. Download jquery.ui.autocomplete.js.

First of all, open Visual Studio 2012. After that, select new project and click on ASP.NET MVC4 Web Application in Visual C#, name the project Autocomplete and whatever you like. Create a controller named HomeController and in this controller, create an ActionResult method named Index.

     public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

     }  

Now create a view, right click on the Index action method and select Add View and then click OK. Write the following code in this view for add a TextBox using @html helper.

  @{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
  @Html.Label("Enter Your name")
  @Html.TextBox("PassId")  

Now, create Action on controller that returns a list of suggestion. Here, I am not using database so I display static data through select item list.

  [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Autocomplete(string term)
        {
            var result = new List<KeyValuePair<string, string>>();

            IList<SelectListItem> List = new List<SelectListItem>();
            List.Add(new SelectListItem { Text = "test1", Value = "0" });
            List.Add(new SelectListItem { Text = "test2", Value = "1" });
            List.Add(new SelectListItem { Text = "test3", Value = "2" });
            List.Add(new SelectListItem { Text = "test4", Value = "3" });

            foreach (var item in List)
            {
                result.Add(new KeyValuePair<string, string>(item.Value.ToString(), item.Text));            
            }
            var result3 = result.Where(s => s.Value.ToLower().Contains(term.ToLower())).Select(w => w).ToList();
            return Json(result3, JsonRequestBehavior.AllowGet);
        } 
Add a model for get set detailed information.
namespace Autocomplete.Models
{
    public class DemoModel
    {
        public int id { get; set; }
        public string name { get; set; }
        public string mobile { get; set; }
    }
}  

Now, add another action result for getting detail information of selected term by id. It takes a parameter name id. Using this id, get detailed information about selected item. It return json object of data. Now get data from json and append it to view controls.

  [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult GetDetail(int id)
        {
            DemoModel model = new DemoModel();
           // select data by id here display static data;
            if (id == 0)
            {
                model.id = 1;
                model.name = "Yogesh Tyagi";
                model.mobile = "9460516787";
            }
            else {
                model.id = 2;
                model.name = "Pratham Tyagi";
                model.mobile = "9460516787";            
            }

            return Json(model);            
        }  

Now you need to add the following JavaScript code to your view that will be call “autocomplete” method of jquery UI whenever you type any char in Textbox. It has two methods, the first is source and another is select. The source method calls when fire “keyup” event of textbox. In source method, we call controller using Ajax This controller method returns a list of suggestion.

When we select a suggestion from list, then another method “select” calls and it also calls controller using Ajax and it return details of selected suggestion.

  <script type="text/javascript">
    $("#PassId").autocomplete({
        source: function (request, response) {
            var customer = new Array();
            $.ajax({
                async: false,
                cache: false,
                type: "POST",
                url: "@(Url.Action("Autocomplete", "Home"))",
                data: { "term": request.term },
                success: function (data) {
                    for (var i = 0; i < data.length ; i++) {
                        customer[i] = { label: data[i].Value, Id: data[i].Key };
                    }
                }
            });
            response(customer);
        },
         select: function (event, ui) {
             //fill selected customer details on form
             $.ajax({
                 cache: false,
                 async: false,
                 type: "POST",
                 url: "@(Url.Action("GetDetail", " Home"))",
                data: { "id": ui.item.Id },

                success: function (data) {
                    $('#VisitorDetail').show();
                    $("#Name").html(data.VisitorName)
                    $("#PatientName").html(data.PatientName)
                    //alert(data.ArrivingTime.Hours)
                    $("#VisitorId").val(data.VisitorId)
                    $("#Date").html(data.Date)
                    $("#ArrivingTime").html(data.ArrivingTime)
                    $("#OverTime").html(data.OverTime)

                    action = data.Action;
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Failed to retrieve states.');
                }
            });
        }
     });

</script>  

Now, run your application and type “t” in Textbox. It looks like:

Select one item from list. It will appear in text box and it calls “select” method of autocomplete that returns detail information about selected information.

History

  • 15th March, 2014: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Yogesh Kumar Tyagi
Software Developer Pure Diets India Limited
India India
No Biography provided
Follow on   Google+

Comments and Discussions

 
QuestionHaving a problem with AutoComplete in mvc5 PinmemberMember 1097923329-Jul-14 10:59 
AnswerRe: Having a problem with AutoComplete in mvc5 PinprofessionalYogesh Kumar Tyagi29-Jul-14 18:58 
QuestionMy Vote of 5* PinprofessionalDeveloper Rahul Sharma23-Jul-14 18:29 
AnswerRe: My Vote of 5* PinprofessionalYogesh Kumar Tyagi23-Jul-14 18:37 
QuestionVery Useful PinmemberDaveBarnett13-Jul-14 8:52 
AnswerRe: Very Useful PinprofessionalYogesh Kumar Tyagi3-Jul-14 17:55 
Questionnice works Pinmemberrajveersingh19-Mar-14 23:29 
AnswerRe: nice works PinprofessionalYogesh Kumar Tyagi7-Jul-14 20:36 
GeneralRe: nice works Pinmemberrajveersingh24-Jul-14 21:15 
GeneralRe: nice works PinprofessionalYogesh Kumar Tyagi24-Jul-14 21:47 
QuestionMy Vote of 5* PinmemberMas1119-Mar-14 22:34 
AnswerRe: My Vote of 5* PinprofessionalYogesh Kumar Tyagi19-Mar-14 23:24 
AnswerRe: My Vote of 5* PinprofessionalYogesh Kumar Tyagi23-Jul-14 18:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140922.1 | Last Updated 19 Mar 2014
Article Copyright 2014 by Yogesh Kumar Tyagi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid