MVC自动完成无法正常工作

时间:2013-02-09 15:29:33

标签: asp.net-mvc autocomplete

我知道那里有很多帖子但只是我无法弄清楚我在自动完成时做错了什么。

我有一个类似

的ProductController
public JsonResult AutocompleteMethod(string searchstring) //searchString null here
        {
              Product ob=new Product();
              List<Product> newLst = ob.GetProducts();
              var suggestions = from s in newLst select s.productName ;
              var namelist = suggestions.Where(n=>n.StartsWith(searchstring));
              return Json(namelist, JsonRequestBehavior.AllowGet);
         }

在视图中我有:

    <p>
        Find by name:<%: Html.TextBox("Txt") %>
    </p>

     <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
     <script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
     <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js" type="text/javascript"></script>


     <script type="text/jscript">
         $(function () {
             debugger;

             $('#Txt').autocomplete({ source: '/Product/AutocompleteMethod' });

         });
     </script>

但控制器功能中始终 SearchString NULL

你能弄明白这是什么错误吗?

1 个答案:

答案 0 :(得分:1)

AFAIK参数名为term,而不是searchstring,因此:

public ActionResult AutocompleteMethod(string term)
{
    List<Product> newLst = new Product().GetProducts();
    var namelist = 
        from p in newLst 
        where p.StartsWith(term)
        select new 
        {
            value = p.Id, // you might need to adjust the Id property name here to match your model
            label = p.productName
        };
    return Json(namelist, JsonRequestBehavior.AllowGet);
}

此外,我非常怀疑productName是自动完成插件将识别的属性。您可以尝试使用valuelabel,如我在示例中执行的投影所示。

相关问题