我从http://www.codeproject.com/Tips/639578/jQuery-Autocomplete-MVC-and-WebAPI下载了自动填充文本框教程的源代码(例如,开始输入,下拉列表将显示与前几个字符相匹配的选项) - 我可以编译它并且它可以完美地运行。
尝试修改它以进行用户名查找,并且我遇到了问题。一切编译好,但下拉不是开始。我错过了一些东西,但我不知道是什么!
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();
}
}
}
控制器:
[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));
}
}
模型(时髦的名字是为了排除其他地方的冲突):
public class ComposeMyMessageModel
{
public string Id { get; set; }
public string Title { get; set; }
public string NewAddress { get; set; }
}
网页:
@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>
路由:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
如果我没有粘贴任何相关的代码,那么因为我不知道它是相关的!将相应更新。感谢。
答案 0 :(得分:1)
您可以在浏览器的网络标签中查看请求和响应,看看您收到了什么吗?还要在success函数中设置断点以验证数据。
这应该指向正确的方向。