The following jQuery autocomplete code is not displaying the results in MVC3. When I debug the code, I can see it is calling the QuickSearchByLastName correctly. Can someone tell me if my code is incorrect? (I also tried with jquery-1.6.2.min.js with no luck) Thank you!
Index.cshtml:
@using (Ajax.BeginForm(new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "results"
}
))
{
<input type="text" name="q" data-autocomplete="@Url.Action("QuickSearchByLastName","Search")" />
}
<div id="results" >
</div>
----------------------------------------------------------------
Search Controller:
public ActionResult QuickSearchByLastName(string term)
{
using (var context = new CSCContext())
{
var searchResults = context.Students
.Where(s => s.LastName.Contains(term) && s.IsActive == true)
.Take(10)
.Select(s => new { label = s.LastName });
return Json(searchResults, JsonRequestBehavior.AllowGet);
}
}
_Layout.cshtml:
@Content.Script("jquery-1.4.4.min.js", Url)
@Content.Script("jquery.unobtrusive-ajax.min.js", Url)
@Content.Script("jquery-ui.min.js", Url)
@Content.Script("jquery.validate.min.js", Url)
@Content.Script("jquery.validate.unobtrusive.min.js", Url)
@Content.Script("CSC.js", Url)
@RenderSection("scripts", false)
CSC.js
$(document).ready(function ()
{
$(":input[data-autocomplete]").each(function ()
{
$(this).autocomplete({
source: $(this).attr("data-autocomplete")
}
);
});
});
The following code fixed the issue:
public ActionResult QuickSearchByLastName(string term)
{
var context = new CSCContext();
try
{
var searchResults = context.Students
.Where(s => s.LastName.Contains(term) && s.IsActive == true)
.Take(10)
.Select(s => new { label = s.LastName });
return Json(searchResults.ToList(), JsonRequestBehavior.AllowGet);
}
finally
{
context.Dispose();
}
}
I have tried replicating your scenario to no avail as it always worked for me. Here’s what I did.
HomeController:
Index.cshtml
I used
jquery-1.5.1.min.jsandjquery-ui-1.8.11.min.jswhich are bundled by default with ASP.NET MVC 3 RTM. I also tried putting this in aAjax.BeginFormand also importing the default unobtrusive scripts and it was still working for me.