17 May 2016 Sudhanshu Ranjan 788

AutoComplete Textbox in ASP.net MVC using Jquery.

Using MVC and jquery you can easily create an autocomplete textbox in Asp.net MVC.

Include JQuery reference and css on page.

     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />

    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>

 

Add textbox on View(Autocomplete.cshtml)

Product: @Html.TextBox("productName")

 

In Controller, Create a function that will return the list of autocomplete values in the JSON format.

public ActionResult Autocomplete()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public JsonResult getData(string term)
        {            
            List<string> lst = new List<string>();
            lst.Add("Sudhanshu");
            lst.Add("NET");
            lst.Add("IT Pathsala");
            lst.Add("Ravi Ranjan");
            lst.Add("Happy");
            lst.Add("Yahoo");

            List<string> getValues = lst.Where(item => item.ToLower().StartsWith(term.ToLower())).ToList();

            // Return the result set as JSON
            return Json(getValues, JsonRequestBehavior.AllowGet);
        }

Add Script on View Page.

<script type="text/javascript">
        $(function ()
        {
            $('#productName').autocomplete({
                source: function (request, response)
                {
                    $.getJSON("/Home/getData?term=" + request.term, function (data)
                    {
                        response(data);
                    });
                },
                minLength: 1,
                delay: 100
            });
        });
    </script>

 

 

 

 

 

You can share at :

About Author
Sudhanshu Kumar Ranjan | Lead Engineer at HCL Technologies | Expertise in Microsoft Technology | Author | Blogger | Programmer
Know More
Connect with him on Facebook | Google+ | LinkedIn | Twitter

Recommended Post

Leave a comment

About Dotnet Cube

It's my blog - Dotnet Cube, where you will learn and get solutions about programming, web designing and development. I started this website to share my knowledge and experience which might help someone.

You can get more details about me and my blog at About Us page.

Subscribe Newsletter

Subscribe to our monthly newsletter to get the latest industry news, Media Group updates and our current specials.

Follow On Us...

Home | About | Advertise | Copyrights | Privacy | Contact | Admin

Copyrights © 2015-2017 dotnetcube.com. All rights reserved