we are implementing Autocomplete Textbox in MVC 5 using jQuery.
The very first step is to create MVC application using visual studio and create database in sql server.
And create table Course in database and call that table in an ASP.Net MVC Application using Entity Framework.
In Controller :
public ActionResult Index() { return View(); } This method is used for autocompete. public JsonResult GetAutoCompete(string Search) { var result = new CourseModel().GetAutoCompete(Search); return Json(result, JsonRequestBehavior.AllowGet); }
In Module: CourseModel.cs
public class Courses1 { public int CourseID { get; set; } public string CourseName { get; set; } } Here we are fetching data (Contains keywords) from records of table course (database ), and getting in list. public class CourseModel{ public List<Course1> GetAutoCompete(string Search) { using (Course Context db = new Course Context()) { var data = (from a in db.Courses where a.CourseName.Contains(Search) // auto populate the records which contain any typed alphabet, for that we are using contains select new { CourseName = a.CourseName, } ).Distinct().ToList(); List<Course1> C = new List<Course1>();foreach (var i in data)
{
Course1 C1 = new Course1 ();
C1.CourseName = i.CourseName;
C1.CourseID = i.CourseID;
C.Add(C1);
}
return C;
}
}
}
In UI html
We are giving reference of jquery(it is required to give reference)
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" /> <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
//jQuery UI to create auto complete textbox in ASP.NET MVC
Html code of text box , where we will enter keywords.
<input type="text" class="form-control input-sm" id="Search" name="Search" placeholder="Search" style="color: white;" /> Script code of autocomplete <script> $(document).ready(function () { $("#Search").autocomplete({ source: function (request, response) { $.ajax({ url: "/Home/GetAutoCompete", type: "POST", dataType: "json", data: { Search: request.term }, success: function (data) { response($.map(data, function (item) { return { label: item.CourseName , value: item.CourseName, }; })) } }) }, messages: { noResults: "No results", results: function (count) { return count + (count == 0 ? ' result' : ' results'); } } });