2010-11-21 29 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