Can't get jQuery autcomplete to work. (ASP.NET MVC)
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.
You need to return your array at the end of the parse
function:
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 };
}
return array; // Add this line
}
The parser method was giving us a headache in a recent project especially with IE 6 & 8. So we opted to use it this way: remenber to add the references:
jQuery Core
<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
jQuery Autocomplete
<link href="../../Scripts/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery.autocomplete.js" type="text/javascript"></script>
try something like this: Controller
public ActionResult Completer(string q)
{
if (q != "")
{
NWDataContext db = new NWDataContext();
var suggest = from i in db.Customers
.Where(e => e.ContactName.ToLower().StartsWith(q.ToLower()))
select (i.ContactName + "|" + i.CustomerID);
return Content(String.Join("\n", suggest.ToArray()));
}
return new EmptyResult();
}
This will return something like :
Ana Trujillo|ANATR
Antonio Moreno|ANTON
Ann Devon|EASTC
Aria Cruz|FAMIA
André Fonseca|GOURL
Annette Roulet|LAMAI
and in your View:
$('#Clientes').autocomplete(' <% =Url.Action("Completer","Home") %>', {
width: 300,
formatItem: formatItem,
formatResult: formatResult
});
and define formatItem and Format result like:
function formatItem(row) {
return row[0] + " (<strong>id: " + row[1] + "</strong>)";
}
function formatResult(row) {
return row[0].replace(/(<.+?>)/gi, '');
}
Hope it helps. You can take a look a this site jquery-plugin-autocomplete-con-asp-net-mvc, its in Spanish but there is a sample project that you can download at the end of the article.
精彩评论