2012-02-11 66 views
2

我有以下方法庫搜索包含搜索參數的用戶: -自動完成是不是在我的asp.net工作MVC

public IEnumerable<User> searchusers2(string q) 
    { 
     return from u in entities1.Users 
       where (u.UserID.Contains(q) || string.IsNullOrEmpty(q)) 
       select u; 
      } 

被稱爲起訴以下操作方法: -

public ActionResult QuickSearch(string term) 
     { 
      var users = r.searchusers2(term); 
      users.Select(a => new { value = a.UserID }); 
      return Json(users, JsonRequestBehavior.AllowGet); 
} 

和上視圖我有以下代碼: -

@using (Ajax.BeginForm("Search", "User", new AjaxOptions 
{ 
    HttpMethod = "POST", 
    InsertionMode = InsertionMode.Replace, 
    UpdateTargetId = "searchResults", 
    LoadingElementId = "progress" 
})) 
{ 

    <input type="text" name="q" data-autocomplete-source="@Url.Action("QuickSearch", "User")" /> 
    <input type="hidden" name="classid" value="@ViewBag.classid"/> 



    <input type="submit" value="Search" /> 
} 

上面的代碼不是WO rking但如果我改變我的操作方法是如下(不使用存儲庫進行搜索),則自動完成將正常工作,,,所以什麼可能導致這個問題: -

public ActionResult QuickSearch(string term) 
     { 
           var users = entities1.Users 
       .Where(e => e.UserID.Contains(term)) 
       .Select(r => new {value = r.UserID }); 
      return Json(users, JsonRequestBehavior.AllowGet); 

     } 

回答

1

在庫版本您在返回的Json整個用戶對象,該Select

public ActionResult QuickSearch(string term) 
{ 
      var users = r.searchusers2(term); 
      users.Select(a => new { value = a.UserID }); 
      return Json(users, JsonRequestBehavior.AllowGet); 
} 

就是什麼也不做,因爲你不保存返回值,你要麼需要產業鏈的召集,如:

public ActionResult QuickSearch(string term) 
{ 
      var users = r.searchusers2(term).Select(a => new { value = a.UserID }); 
      return Json(users, JsonRequestBehavior.AllowGet); 
} 

或使用單獨的變量:

public ActionResult QuickSearch(string term) 
{ 
      var users = r.searchusers2(term); 
      var values = users.Select(a => new { value = a.UserID }); 
      return Json(values, JsonRequestBehavior.AllowGet); 
}