代码之家  ›  专栏  ›  技术社区  ›  Junior Mayhé

WCF和jQuery自动完成插件

  •  1
  • Junior Mayhé  · 技术社区  · 14 年前

    下午好

    autocomplete plugin 让它使用我的WCF服务方法。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

    jquery 自动完成

    1 回复  |  直到 14 年前
        1
  •  2
  •   Cheeso    14 年前

    我只是把这个编码在一起,用 the autocomplete from jQuery UI v1.8rc3 (我认为这是一个旧版本;它与jQuery 1.4.2和WCF 3.5(还有一个版本过期)一起工作。我是这样做的。

    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>
    

    <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>
    

    这很管用。


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