2010-11-21 28 views
1

我想使用jQuery UI,但我似乎无法弄清楚如何让select事件执行。在JQuery UI上选择事件autocompleter没有被解雇

我的autocompleter绑定如下:

$().ready(function() { 
    $("#txtPersonSearch").autocomplete({ 
     source: '<%=Url.Action("GetPeople") %>', 
     minLength: 3, 
     select: function (event, ui) { 
      // This code is never reached 
      console.log(ui); 
     } 
    }); 
}); 

我缺少的东西是能够绑定到select事件?

回答

2

也许您的控制器操作会引发异常。让我们采取以下措施:

public ActionResult GetPeople(string term) 
{ 
    // the term parameter will contain the search string 
    // TODO: use the term parameter to filter the results from 
    // your repository. In this example the result is hardcoded 
    // to verify that the everything works. 
    return Json(new[] 
    { 
     new { id = "1", label = "label 1", value = "value 1" }, 
     new { id = "2", label = "label 2", value = "value 2" }, 
     new { id = "3", label = "label 3", value = "value 3" }, 
    }, JsonRequestBehavior.AllowGet); 
} 

事情需要提防:

  • 控制器的动作是GET动词访问(JsonRequestBehavior.AllowGet
  • 控制器动作返回一个JSON数组,其中每个项目都有标识和值属性
  • 控制器操作不会抛出异常

然后:

$(function() { 
    $('#txtMovieSearch').autocomplete({ 
     source: '<%= Url.Action("GetPeople") %>', 
     minLength: 3, 
     select: function (evt, ui) { 
      console.log(ui); 
     } 
    }); 
}); 

最后使用FireBug来分析究竟是发送到您的服务器作为一个AJAX请求和服务器的响应。

+0

你是对的!它使用了更简单的JSON返回。我的控制器返回一个字典有麻烦序列化到JSON吗? – Dofs 2010-11-21 17:41:19

+0

看看我的例子。序列化字典不会有问题,但插件理解响应会有麻烦。它需要按照我的例子进行格式化。因此,在字典上使用简单的'.Select()'扩展方法可以实现所需的结果:'return Json(dico.Select(x => new {id = x.Key,label = x.Value,value = x.Value}),JsonRequestBehavior.AllowGet);' – 2010-11-21 17:44:02

+0

非常感谢您的帮助! – Dofs 2010-11-21 17:48:39