简体   繁体   中英

jQuery Autocomplete, MVC4, and WebAPI

I downloaded the source code for a tutorial on autocompleting text boxes (eg start typing and a drop-down will appear with options matching those first few characters) from http://www.codeproject.com/Tips/639578/jQuery-Autocomplete-MVC-and-WebAPI - I can compile it and it works perfectly.

Trying to adapt it for a username lookup and I'm having problems. Everything compiles okay but the drop-down is not firing. I'm missing something but I've no idea what!

ApiController:

public class UserApiController : ApiController
{
    [HttpGet]
    public IEnumerable<ApplicationUser> GetUsers(string query = "")
    {
        using (var db = new ApplicationDbContext())
        {
            return String.IsNullOrEmpty(query) ? db.Users.ToList() :
            db.Users.Where(p => p.UserName.Contains(query)).ToList();
        }
    }
}

Controller:

    [HttpGet]
    public ActionResult Search()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Search(ApplicationUser user)
    {
        return RedirectToAction("Details", "PrivateMessage", new { Id = user.Id });
    }

    public ActionResult Details(string Id)
    {
        using (var db = new ApplicationDbContext())
        {
            return View(db.Users.FirstOrDefault(p => p.Id == Id));
        }
    }

Model (the funky name was to rule out clashes elsewhere):

public class ComposeMyMessageModel
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string NewAddress { get; set; }
}

Web page:

@model MyWebsite.Models.ComposeMyMessageModel

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

@{
  ViewBag.Title = "Compose";
}
@using (Html.BeginForm()){
  @Html.HiddenFor(model => model.Id)
  <input type="text" id="search" placeholder="Search for a product" required />
  <input type="submit" value="Go" id="submit" />
}

<script type="text/javascript">
    var url = '@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "UserApi" })';
    $('#search').autocomplete({
        source: function (request, response) {
          $.ajax({
             url: url,
             data: { query: request.term },
             dataType: 'json',
             type: 'GET',
             success: function (data) {
                 response($.map(data, function (item) {
                     return {
                         label: item.Description,
                         value: item.Id
                     }
                 }));
             }
         })
     },
      select: function (event, ui) {
         $('#search').val(ui.item.label);
         $('#Id').val(ui.item.value);
         return false;
      },
     minLength: 1
   });
</script>  

Routing:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

If I haven't pasted any code that is relevant then it's because I didn't know it was relevant! Will update accordingly. Thanks.

Can you view the request and response in the browser's network tab to see what you're getting? Also set a breakpoint in the success function to verify the data.

That should point you in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM