自动完成在我的asp.net MVC中无效

时间:2012-02-11 22:34:11

标签: asp.net-mvc-3 autocomplete

我有以下存储库方法来搜索包含搜索参数的用户: -

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" />
}

上面的代码无法正常工作,但是如果我将我的操作方法改为如下(不使用存储库来执行搜索),那么自动完成将正常工作,因此可能导致此问题: - < / p>

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 个答案:

答案 0 :(得分:1)

在存储库版本中,您将返回Json中的整个User对象,

中的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);
}