Junaid Junaid - 7 months ago 721
Javascript Question

Jquery autocomplete not working on ASP.NET MVC 5


  • Tutorial I am following



Hi, I am implementing jquery autocomplete using this tutorial
ASP.NET Tutorial Part 76 Implement autocomplete textbox functionality in mvc
https://www.youtube.com/watch?v=MmBdMZJ3Jlo


  • Problem



When I type something in input box, autocomplete does not work


  • Description



I have implemented the search functionality and its working fine but i am stuck on autocomplete function of jquery. I have searched a lot on google and stack overflow previous questions, i tried everything but couldn't solve my problem.


  • Code



Here is my code of autocomplete ( i have not included code of searching )

Index.cshtml

<link href="~/Content/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="~/Content/jquery-ui.min.css" rel="stylesheet" type="text/css" />

<script src="~/Scripts/jquery-2.1.4.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: '@Url.Action("GetAirports")'
});
});

</script>

@using(@Html.BeginForm())
{
<br />
<b>AirPort Code:</b>
@Html.TextBox("SearchTerm", null, new { id="txtSearch"})
<input type="submit" value="Search" />
}


and my controller code

HomeController.cs

public JsonResult GetAirports(string term)
{
traveloticketEntities db = new traveloticketEntities();
List<String> Airports = new List<String>();
Airports = db.IataAirportCodes.Where(x => x.code.StartsWith(term)).Select(y=>y.code).ToList();
return Json(Airports, JsonRequestBehavior.AllowGet);

}

Answer

I got the solution. Thanks a lot @mason for your help. I checked my code on client side console (google chrome console using F12) and there i found out that _Layout.cshtml were adding other jQuery libraries at the end of my index.cshtml file, which were overwriting my libraries in index.cshtml. So i removed this code from _Layout.css

 @Scripts.Render("~/bundles/jquery")
 @Scripts.Render("~/bundles/jqueryval")

and placed my jQuery libraries in Index.cshtml in the following order

<script src="~/Scripts/external/jquery/jquery.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.11.4.js" type="text/javascript"></script>
<script src="~/Scripts/myScript.js" type="text/javascript"></script>