I'm trying to implement my first every quick-search feature that shows possible results in a dropdown as you type. I think I'm really close. But for some reason, the quick results just don't show in the browser.
Here's the code in the View:
@using (Ajax.BeginForm("Search", "Home", new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.ReplaceWith,
UpdateTargetId = "searchResults"
}))
{
<input type="text" name="q" data-autocomplete="@Url.Action("QuickSearch", "Home")" />
<input type="submit" value="Search" />
}
<table id="searchResults"></table>
And then the HTML that is sent to the browser:
<form action="/Home/Search" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace-with" data-ajax-update="#searchResults" id="form0" method="post">
<input type="text" name="q" data-autocomplete="/Home/QuickSearch" class="ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
<input type="submit" value="Search">
</form>
<table id="searchResults"></table>
I can put a break point over the method in the controller that queries the DB, and using Watch, I can see that it brings back accurate results with each key press:
public ActionResult QuickSearch(string term)
{
var restaurants = _db.Restaurants
.Where(r => r.Name.Contains(term))
.Take(10)
.Select(r => new { label = r.Name });
return Json(restaurants, JsonRequestBehavior.AllowGet);
}
And finally, here's the JavaScript that should tie it all together:
/// <reference path="jquery-1.4.4-vsdoc.js" />
/// <reference path="jquery-ui.js" />
/// <reference path="jQuery.tmpl.js" />
$(document).ready(function () {
$(":input[data-autocomplete]").each(function () {
$(this).autocomplete({ source: $(this).attr("data-autocomplete") });
});
$(":input[data-datepicker]").datepicker();
$("#searchForm").submit(function () {
$.getJSON($(this).attr("action"), // the url to get JSON from
$(this).serialize(), // make q=yellow, for example
function (data) { // what to do with the response
var result = $("#searchTemplate").tmpl(data);
$("#searchResults").empty()
.append(result);
}
);
return false;
});
})
I am including the scripts:
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/respond.js"></script>
<script src="/Scripts/jquery-ui.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
Also... this may be part of the same issue... Not only do the quick-results not show in the dropdown under the screen, but when I click "Search", the results show in an empty screen, and not in the original View as expected.