2013-02-09 95 views
0

我知道那裏有很多帖子,但只是我無法弄清楚我在自動完成中做了什麼錯誤。MVC自動完成功能不起作用

我有一個像

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

鑑於一個ProductController的我:

<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

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,如我在示例中執行的投影中所示。

+0

非常感謝nuch.It工作。 – 2013-02-09 15:48:53