AutoComplete using ASP.NET MVC and Jquery

AutoComplete means when you type something in textbox you will get results from database or any other source. In AutoComplete functionality we have to add one CSS Jquery-ui.css and one javascript file Jquery-ui.js.

On the view you have to add one textbox where you type characters like below code

<input type="text" name="txtsearch" data-urltofire="@Url.Action("Search", "Home")" />

And simply create another javascript file say autosearch.js and add code like below:

$(document).ready(function ()
{
    $("#txtsearch").autocomplete({ source: $("#txtsearch").attr("data-urltofire") });
})

In the above code autocomplete function call the controller and action method specified in source attribute.

So now we have to create action method with name Search in the Home Controller.

namespace MvcApplication7.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Search(string search)
        {
            //Here you can write code to select data source from DB that match search condition and return the datasource
            return Json(datasource, JsonRequestBehavior.AllowGet);
        }
    }
}

This action method returns result in the form of json so Jquery can easily read it and bind to that textbox.



See below link for related articles

1.       Getting Started with MVC


2.      ViewBag, ViewData and TempData


3.       Folder Structure In MVC


4.       MVC Architecture Theory


5.       Data Annotations and Validations in MVC


6.       MVC Architecture: Traditional Routes


7.       MVC Architecture: Attribute based Routing


8.       Bundling and Minification in MVC


9.       AutoComplete in MVC

                    http://dotnet-root.blogspot.in/2016/10/autocomplete-using-aspnet-mvc-and-jquery.html


10.       Adding Controller, Model and Views

                      http://dotnet-root.blogspot.in/2016/11/adding-controller-model-and-view-in.html


Post a Comment

0 Comments