peggy peggy -4 years ago 148
jQuery Question

MVC Autocomplete Dropdown Troubles

I am currently trying to use Jquery-UI's autocomplete functionality similar to as shown here: Autocomplete dropdown in MVC5? ... I have reviewed many posts now using jquery autocomplete helper and have been unable to find my issue. My problem is that the ajax call goes out and succesfully hits the GetSchools action, the action will return the correct and expected data, but then nothing happens. No autocomplete options are displayed and no console errors appear. The

success
function in my js gets hit with the appropriate number of items in
data
but nothing happens after that. All help is appreciated.

My Controller Actions:

public ActionResult ManualVerifications()
{
var vm = new ManualVerificationsViewModel();

return View(vm);
}

[HttpPost]
public ActionResult ManualVerifications(ManualVerificationsViewModel vm)
{
return View();
}

public JsonResult GetSchools(string term = "")
{
var schoolList = _schoolRepo.GetAll()
.Where(c => c.Name.ToLower().Contains(term.ToLower()))
.Select(x => new { label = x.Name, value = x.Id })
.Distinct().ToList();

return Json(schoolList, JsonRequestBehavior.AllowGet);
}


My View (ManualVerifications.cshtml):

@model ProEdVerificationPortal.Data.ViewModels.Verification.ManualVerificationsViewModel

@Html.LabelFor(model => model.SelectedSchoolName, new { @class = "control-label" })
@Html.TextBoxFor(model => model.SelectedSchoolName, new { @class = "form-control" })
@Html.HiddenFor(model => model.SchoolId)


and the JS rendered in the view:

$(document).ready(function () {
$("#SelectedSchoolName").autocomplete({
source: function (request, response) {
$.ajax({
url: '/verification/getschools',
type: "GET",
datatype: "json",
data: {
term: request.term
},
success: function (data) {
console.log(data);
response(data);
}
})
},
select: function (event, ui) {
$("#SelectedSchoolName").val(ui.item.label);
$("#SchoolId").val(ui.item.value);
return false;
},
focus: function (event, ui) {
$("#SelectedSchoolName").val(ui.item.label);
return false;
}
});
});


and my very simple viewmodel:

public class ManualVerificationsViewModel
{
public string SelectedSchoolName { get; set; }

public int SchoolId { get; set; }
}


an example of data return from my controller would be the following:
[ { label: "SeedSchool", value: 1 }


and a picture from the console.log(data) results:
enter image description here

Answer Source

Looks like you're result data is not correct. Based on the following:

public JsonResult GetSchools(string term = "")
{
  var schoolList = _schoolRepo.GetAll()
    .Where(c => c.Name.ToLower().Contains(term.ToLower()))
    .Select(x => new { Name = x.Name, Id = x.Id })
    .Distinct().ToList();

  return Json(schoolList, JsonRequestBehavior.AllowGet);
}

I would expect your resulting data set is like:

[{
  "Name": "Berkley",
  "Id": 1001
},
{
  "Name": "UCSF",
  "Id": 1002
}]

Autocomplete does not know what to do with this data. It's especting an array with specific object data:

An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

You'll want to adjust your results to fit this format.

public JsonResult GetSchools(string term = "")
{
  var schoolList = _schoolRepo.GetAll()
    .Where(c => c.Name.ToLower().Contains(term.ToLower()))
    .Select(x => new { label = x.Name, value = x.Id })
    .Distinct().ToList();

  return Json(schoolList, JsonRequestBehavior.AllowGet);
}

And:

$(document).ready(function () {
  $("#SelectedSchoolName").autocomplete({
    source: function (request, response) {
      $.ajax({
        url: '/verification/getschools',
        type: "GET",
        datatype: "json",
        data: {
          term: request.term
        },
        success: function (data) {
          response(data);
        }
      })
    },
    select: function (event, ui) {
      $("#SelectedSchoolName").val(ui.item.label);
      $("#SchoolId").val(ui.item.value);
      return false;
    },
    focus: function( event, ui ) {
      $("#SelectedSchoolName").val(ui.item.label);
        return false;
      }
    }
  });
});

Update 1

Including a lite example: https://jsfiddle.net/Twisty/4Lv9psd8/

Update 2

An example with AJAX functionality and some other flare: https://jsfiddle.net/Twisty/4Lv9psd8/6/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download