2010-11-06 82 views
1

下午好WCF和jQuery自動完成插件

我面臨一個麻煩,試圖找出如何使用這個autocomplete plugin,並使其消耗我的WCF服務的方法。 WCF正確發佈和工作。

什麼可以做到自動完成插件的工作,還是有另一種聰明的方式使WCF的自動完成工作,並獲得選擇Person.Id和Person.Name?

下面有些事情我已經工作到現在:

WCF服務

public class Person { 
    public int Id {get;set;} 
    public string Name {get;set;} 
    public static List<Person> List(){ 
     /*long query supressed to no be annoying :) */ 
    } 
} 

[ServiceContract] 
public interface IChatService 
{ 
    [OperationContract] 
    [WebInvoke(Method = "GET", 
    UriTemplate = "GetPeople", 
    BodyStyle = WebMessageBodyStyle.Bare, 
    ResponseFormat = WebMessageFormat.Json)] 
    List<Person> GetPeople(); 
} 

public class MyService : IMyService 
{ 
    public List<Person> GetPeople() 
    { 
     return Person.List(); 
    } 
} 

現在aspx頁面:

.... 
<head> 
<script type="text/javascript" src="http://view.jquery.com/trunk/plugins/autocomplete/lib/jquery.js"></script> 
<script type='text/javascript' src='http://view.jquery.com/trunk/plugins/autocomplete/lib/jquery.bgiframe.min.js'></script> 
<script type='text/javascript' src='http://view.jquery.com/trunk/plugins/autocomplete/lib/jquery.ajaxQueue.js'></script> 
<script type='text/javascript' src='http://view.jquery.com/trunk/plugins/autocomplete/lib/thickbox-compressed.js'></script> 
<script type='text/javascript' src='http://view.jquery.com/trunk/plugins/jquery.autocomplete.js'></script> 
<link rel="stylesheet" type="text/css" href="http://view.jquery.com/trunk/plugins/jquery.autocomplete.css" /> 
<link rel="stylesheet" type="text/css" href="http://view.jquery.com/trunk/plugins/lib/thickbox.css" /> 

<script> 
    $().ready(function() { 
     $('#<%=peopleNames.ClientID%>').autocomplete("http://localhost/MyService/MyService.svc/GetPeople", { 
      width: 260, 
      selectFirst: false 
     }); 
     $("#<%=peopleNames.ClientID%>").result(function (event, data, formatted) { 
      alert('ok'); 
      if (data) { 
       alert($(this).parent().next().find("input").val(data[1])); 
      } 
     }); 
    }); 

</script> 
</head> 
<body> 
<form runat="server"> 
<asp:TextBox ID="peopleNames" runat="server" MaxLength="500"></asp:TextBox> 
</form> 
</body> 
</html> 

只是用於測試目的,想法是讓Web用戶鍵入一個名稱,並且jQuery將調用WCF服務http://localhost/MyService/GetPeople列出SQL Server數據庫中的所有人員(將來的GetPeople方法將有一個字符串參數)。

jquery 自動完成插件似乎很好,但我不確定哪些js文件需要在我的本地計算機上工作。現在我不能使它工作或調試它,即使它顯示alert();

+0

那麼Person Class中的[DataConctract] [DataMember]屬性呢? – mmutilva 2010-11-06 18:42:22

+0

完成。我看到WCF運行良好。我正在看http://jqueryui.com/demos/autocomplete/#remote看看發生了什麼 – 2010-11-06 19:07:03

回答

2

我剛剛編碼在一起,使用the autocomplete from jQuery UI v1.8rc3(我認爲這是一箇舊版本;它適用於jQuery 1.4.2)和WCF 3.5(也是一個過時的日期)。這是我做過的。

WCF服務

using System; 
using System.Linq; 
using System.Collections.Generic; 
using System.ServiceModel; 
using System.ServiceModel.Web; 
using System.Runtime.Serialization; 

namespace Ionic.Samples.Webservices._2010.Nov 
{ 
    [ServiceContract(Namespace="urn:Ionic.Samples")] 
    public interface ICompletionService 
    { 
     [OperationContract] 
     [WebInvoke(Method = "GET", 
        RequestFormat=WebMessageFormat.Json, 
        ResponseFormat = WebMessageFormat.Json, 
        UriTemplate = "getcompletions/{fragment}")] 
     List<String> GetCompletions(string fragment); 
    } 


    [ServiceBehavior(Name="WcfJqueryAutoComplete", 
        Namespace="urn:Ionic.Samples", 
        InstanceContextMode=InstanceContextMode.Single, // one instance for all requests 
        IncludeExceptionDetailInFaults=true)] 

    public class WcfJqueryAutoComplete : ICompletionService 
    { 
     private List<String> allCandidates; 

     public WcfJqueryAutoComplete() 
     { 
      allCandidates = new List<String> 
       { 
      "January", "February", "March", "April", "May", "June", 
      "July", "August", "September", "October", "November", 
      "December", "Yammer", "Yaw", "Yawn", "Auspiscious", 
      "Arbitrage", "Arbiter", "Arbor", "Ardor", "Ardent", 
      "Concrete", "Conscious", "Uptight", "Uplevel", "Friend", 
      "Depend", "Deepend", "Deepen", "Decommit", "Right", "Now", 
      "Knowledge", "Knight", "Know", "Knickers", "Wow", "Holy", 
      ... 
       }; 
     } 

     public List<String> GetCompletions(String fragment) 
     { 
      var frag = fragment.ToUpper(); 
      // use LINQ to select candidates from the in-memory list. 
      // You could replace this with a SQL query. 
      var selection = from candidate in allCandidates 
       where candidate.ToUpper().StartsWith(frag) 
       select candidate; 

      return new List<String>(selection); 
     } 
    } 
} 

.svc文件

<%@ ServiceHost 
Language="C#" 
Debug="true" 
Service="Ionic.Samples.Webservices._2010.Nov.WcfJqueryAutoComplete" 
%> 

有關的WCF的.config信息

<system.serviceModel> 

    <behaviors> 
    <endpointBehaviors> 
     <behavior name="JsonServiceEndpointBehavior"> 
     <webHttp /> 
     </behavior> 
    </endpointBehaviors> 
    </behaviors> 


    <services> 
    <service 
     name="Ionic.Samples.Webservices._2010.Nov.WcfJqueryAutoComplete" 
     > 
     <endpoint 
     address    = "" 
     binding    = "webHttpBinding" 
     contract    = "Ionic.Samples.Webservices._2010.Nov.ICompletionService" 
     behaviorConfiguration = "JsonServiceEndpointBehavior" 
     bindingNamespace  = "urn:Ionic.Samples" 
     /> 

    </service> 
    </services> 
</system.serviceModel> 

JavaScript的邏輯

<script type="text/javascript"> 
    <!-- 

    var ajaxUrlBase1 = "/services/WcfJqueryAutoComplete.svc/"; 

    $(document).ready(function() { 

     $("#input1").autocomplete({ 
      // The source option can be an array of terms. In this case, if 
      // the typed characters appear in any position in a term, then the 
      // term is included in the autocomplete list. 
      // The source option can also be a function that performs the search, 
      // and calls a response function with the matched entries. 
      source: function(req, responseFn) { 
       $.ajax({ 
        url  : ajaxUrlBase1 + "getcompletions/" + req.term, 
        cache : false, 
        type : "GET", // http method 
        dataType: "json", 
        error : function(XMLHttpRequest,status,error){ 
         alert("Error p1 s(" + status + ") e(" + error + ")"); 
        }, 

        success : function(msg, arg2, xhr){ 
         try { 
         if (msg !== null) { 
          responseFn(msg); 
         } else { 
          alert("msg is null"); 
         } 
         } 
         catch(e) { 
         alert("exception: " + e); 
         } 
        } 
       }); 
      }, 

      select: function(value, data){ 
      // whatever you like here 
      } 
     }); 
    }); 

    --> 
</script> 

這工作得很好。 ps:對於調試jQuery,我發現包含在FF或IE8 +中的調試工具是非常寶貴的。在IE8中按F12來獲得調試器控制檯。

此外,在開發時,我經常設置一個div,id = msgs,從javascript邏輯收集診斷信息。然後,我使用這種功能在執行的不同階段放入信息。

function addMessage(msg, clear){ 
    if (clear !== null && clear) { 
     $('#msgs').html(""); 
    } 
    $('#msgs').append("<p>" + msg + "</p>"); 
} 
+0

謝謝你的答案。這裏奇怪的是'$('#example')。autocomplete(source:function(request,response){$ .ajax({...')永遠不會被觸發,但是當我把'$(' #example')。autocomplete(myDataArray)'it works。 – 2010-11-08 00:24:04

+0

對不起,我不知道你的意思。什麼是永遠不會被「解僱」的? – Cheeso 2010-11-08 02:15:40

+0

源碼嵌套函數'.ajax(...'但是你的回答幫助我以另一種方式,現在我在閱讀Google代碼http://code.google.com/p/jquery-autocomplete/wiki/Documentation中的自動完成插件文檔後自動完成工作。以下是我的工作示例: http://stackoverflow.com/questions/4173999/jquery-ajax-call-working-and-autocomplete-not-working-with-wcf/4174878#4174878 – 2010-11-13 21:45:26