New to ASP.NET MVC and programming, and I have searched high and low for materials on this subject but haven’t found a concrete answer for my particular problem.
The project I am working on requires the use of WCF services. Initially I started with a jQuery autocomplete function that worked, however moving the code to a WCF service has broken some communication. The autocomplete functionality no longer works
WCF Service
public IList<Location> QuickSearchLocation(string term)
{
using (var db = new InspectionEntities())
{
//return all locations except the reserved "Other"
return db.Locations
.Where(r => r.LocationName.Contains(term) && r.LocationId != Constants.OtherId)
.ToList();
}
}
The above code is meant to takes user input based on relation to child table. If user input does not match data in child table, the users entry is saved to an “other” column in the main db.
Controller
public ActionResult QuickSearchLocation(string term)
{
return Json(_service.QuickSearchLocation(term), JsonRequestBehavior.AllowGet);
}
View
div class="editor-field">
@Html.TextBoxFor(m=>m.LocationId,new {data_autocomplete = Url.Action("QuickSearchLocation", "Inspection")})
script
$(document).ready(function () {
$(":input[data-autocomplete]").each(function () {
$(this).autocomplete({ source: $(this).attr("data-autocomplete")});
});
Any insight on my problem would be helpful.
Autocomplete expects either only labels or labels with values. On the other hand, you’re serving it the whole
Locationobject.You should therefore, create a helper class:
After this, you should change your
QuickSearchLocationcontroller method like this:You should also consider not returning all the results but, rather, only first few (10 for example).