Reputation: 59
I am having a problem getting a search form to autocomplete in MVC4 razor, using jQuery and AJAX.
My HTML Form
@using (Html.BeginForm())
{
@Html.TextBox("FriensList")
<input type="submit" value="Go" />
}
My JS Script
$(document).ready(function () {
$("#FriensList").autocomplete({
source: function(request,response) {
$.ajax({
url: "/User/FriendList",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.label };
}))
}
})
},
minLength: 1,
delay: 1000
});
})
and my controller
public ActionResult FriendList(string term)
{
using (var db = new dbContext())
{
var result = db.UserProfiles
.Where(r => r.FirstName.Contains(term))
.Take(10)
.Select(r => new {label = r.FirstName});
return Json(result, JsonRequestBehavior.AllowGet);
}
}
Debugging the code, I can see that it enters the action when I type a letter into the search box, which returns the correct data from the database, but when the ajax receives the response, it seems to give a 500 error.
I have ensured that my script is being loaded after the js bundles and I added minLength and Delay parameters as suggested in similar question that were previously asked.
Thanks for any help.
Edit 1
I changed the controller to
public ActionResult FriendList(string term)
{
using (var db = new dbContext())
{
var result = db.UserProfiles
.Where(r => r.FirstName.Contains(term))
.Take(10)
.Select(r => new {label = r.FirstName});
var ser = new JavaScriptSerializer();
var tests = ser.Serialize(result);
return Json(tests, JsonRequestBehavior.AllowGet);
}
}
now when I search I get a load of li tags under the searchbox. It doesnt print any text, but seems to be repeating over something that isn't the results
Edit 2
I changed the return to
return Json(tests, "Label", JsonRequestBehavior.AllowGet);
and the following ajax
return { label: item};
and now it prints out each separate character in a separate line, including the json brackets
Upvotes: 0
Views: 1788
Reputation: 5469
Json
method internally serializes data to JSON format, so you dont have to explicitly serialize the data.
//var ser = new JavaScriptSerializer();
//var tests = ser.Serialize(result);
return Json(result.ToList(),JsonRequestBehavior.AllowGet);
The first draft did not work because result
was of type IQueryable<T>
which is not the data but a query expression. To explicitly collect data from the query expression .ToList()
method needs to be called, hence result.ToList()
.
hope this helps.
Upvotes: 1