Hi,
I'm trying to follow the example in this post by tvanfosson. I just can't get it to work. I think the problem is with my JavaScript (?). I say that because if I navigate in my browser to http://localhost:49790/Books/GetBooks/?q= then the browser downloads a file with the information that I'd expect in the format I'd expect:
[{"BookName":"Book 1","AuthorName":"Author 1","BookID":2},{"BookName":"Book 2","AuthorName":"Author 2","BookID":3}]
But back on the view, when I start typing in the SearchBox, nothing happens. No autocomplete.
Here is my view:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
jQuerySearch
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function() {
$('#SearchBox').autocomplete('/Books/GetBooks', {
dataType: 'json',
max: 25,
minChars: 1,
cacheLength: 1,
mustMatch: true,
formatItem: function(data, i, max, value) {
return value;
},
parse: function(data) {
var array = new Array();
for (var i = 0; i < data.length; i++) {
var datum = data[i];
var display = datum.AuthorName + ' - ' + datum.BookName;
array[array.length] = { data: datum, value: display, result: display };
}
}
});
$('#SearchBox').result(function(event, data, formatted) {
if (data) {
$('#BookID').val(data.BookID);
}
});
$('form').submit(function() {
if (!$('#BookID').val()) {
alert('You must select a book before clicking submit!');
return false;
}
});
});
</script>
<h2>jQuerySearch</h2>
<%using (Html.BeginForm()){%>
<%=Html.TextBox("SearchBox") %>
<input type='hidden' id='BookID' name='BookID' />
<%}; %>
</asp:Content>
Here is my controller code:
public ActionResult GetBooks(string q)
{
var query = db.Books.Where(e => e.Name.Contains(q))
.OrderBy(e => e.Name)
.Select(e => new
{
BookName = e.Name,
AuthorName = e.Author.Name,
BookID = e.BookID
});
return Json(query.ToList());
}
I'm pretty new to all this. Any help is appreciated.
Thanks.