50

jQuery と ASP.NET を使用したオートコンプリートの簡単な例を、このサイトと Web で検索しました。オートコンプリートで使用されるデータを Web サービスで公開したかった (おそらく次に行う予定です)。それまでの間、私はこれを機能させましたが、少しハッキーなようです...

私のページにはテキストボックスがあります:

<input id="txtSearch" type="text" />

私はjQueryオートコンプリートを使用しており、例に従って設定しています:

<link rel="stylesheet" href="js/jquery.autocomplete.css" type="text/css" />
<script type="text/javascript" src="js/jquery.bgiframe.js"></script>
<script type="text/javascript" src="js/jquery.dimensions.pack.js"></script>
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>

ハッキングが始まるのはここからです...私はWebサービスの代わりにページを呼び出します:

  <script type="text/javascript">
    $(document).ready(function(){
        $("#txtSearch").autocomplete('autocompletetagdata.aspx');
    });      
  </script>

このページでは、すべての html を取り除き、これだけを作成しました (そうしないと、さまざまな HTML ビットがオートコンプリート ドロップダウンに表示されます)。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="autocompletetagdata.aspx.cs" Inherits="autocompletetagdata" %>

また、私の autocompletetagdata.aspx では、SubSonic を使用してデータベースからデータをクエリ、フォーマット、および返しています (1 行に 1 つのデータ項目)。

protected void Page_Load(object sender, EventArgs e)
{
    // Note the query strings passed by jquery autocomplete:
    //QueryString: {q=a&limit=150&timestamp=1227198175320}

    LookupTagCollection tags = Select.AllColumnsFrom<LookupTag>()
        .Top(Request.QueryString["limit"])
        .Where(LookupTag.Columns.TagDescription).Like(Request.QueryString["q"] + "%")
        .OrderAsc(LookupTag.Columns.TagDescription)
        .ExecuteAsCollection<LookupTagCollection>();

    StringBuilder sb = new StringBuilder();

    foreach (LookupTag tag in tags)
    {
        sb.Append(tag.TagDescription).Append("\n");
    }

    Response.Write(sb.ToString());
}

LIKE クエリを実行しない場合は、入力した文字に一致するものをすべて返します。たとえば、「a」と入力すると、「Ask」と「Answer」、「March」と「March」が含まれます。 「メガ」私はそれが最初から試合をしたかっただけです。

とにかく、それは機能し、セットアップは非常に簡単ですが、より良い方法はありますか?

4

4 に答える 4

32

最近オートコンプリートを実装しましたが、かなり似ています。aspx の代わりに ashx (Generic Handler) を使用していますが、コード ビハインドでは基本的に同じコードです。

ashx を使用すると、次のようになります。

<script type="text/javascript">
  $(document).ready(function(){
      $("#txtSearch").autocomplete('autocompletetagdata.ashx');
  });      
</script>

[WebService(Namespace = "http://www.yoursite.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class AutocompleteTagData : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Note the query strings passed by jquery autocomplete:
        //QueryString: {q=a&limit=150&timestamp=1227198175320}

        LookupTagCollection tags = Select.AllColumnsFrom<LookupTag>()
            .Top(context.Request.QueryString["limit"])
            .Where(LookupTag.Columns.TagDescription).Like(context.Request.QueryString["q"] + "%")
            .OrderAsc(LookupTag.Columns.TagDescription)
            .ExecuteAsCollection<LookupTagCollection>();

        foreach (LookupTag tag in tags)
        {
            context.Response.Write(tag.TagDescription + Environment.NewLine);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
于 2008-11-20T16:56:57.270 に答える
10

これを別の質問に投稿しましたが、jQuery オートコンプリート プラグインの解析関数をオーバーライドして、任意の出力をサポートすることができます。

例:

    $("#<%= TextBox1.ClientID %>").autocomplete("/Demo/WebSvc.asmx/SuggestCustomers", {
        parse: function(data) {
            var parsed = [];

            $(data).find("string").each(function() {
                parsed[parsed.length] = {
                    data: [$(this).text()],
                    value: $(this).text(),
                    result: [$(this).text()]
                };
            });
            return parsed;
        },
        dataType: "xml"
    });

これが期待するのは XML への文字列配列だけです... 非常に簡単に実行できます... SubSonic を使用している場合は、RESTHandler を確認する必要があります (これは隠された GEM です!!!)。これは、すべてのオブジェクトに対する基本的なクエリをサポートし、 JSON/XML を返します。これを使用したクエリの例を次に示します...

/Demo/services/Customers/list.xml?CustomerName=JOHN

list.xml を list.json に変更すると、結果が JSON に変更されます。上記のリクエストは、厳密に型指定された「Customer」エンティティを返します。パラメータを変更して、LIKE、NOT LIKE などをサポートすることができます...非常に強力で、すべての配管は既に完了しています...

ここにビデオがあります: http://subsonicproject.com/tips-and-tricks/webcast-using-subsonic-s-rest-handler/

于 2009-05-27T19:03:26.983 に答える
6

WebサービスまたはWCFサービスは、より優れたインターフェイスの可能性を提供します。どちらも、Jsonシリアル化を行うように設定できます。

執筆中にWCFクラスを使用しているので(本当に休憩中です!)、WCFメソッドをスケッチします。

[OperationContract]
[WebInvoke(RequestFormat=WebMessageFormat.Json,
           ResponseFormat=WebMessageFormat.Json)]
public LookupTagCollection LookupTags( int limit, string q )
{
     return Select.AllColumnsFrom<LookupTag>()
                  .Top(limit)
                  .Where(LookupTag.Columns.TagDescription)
                  .Like(q+ "%")
                  .OrderAs(LookupTag.Columns.TagDescription)
                  .ExecuteAsCollection<LookupTagCollection>();    
}

LookupTagCollectionはシリアル化可能である必要があります。

于 2008-11-20T17:09:07.327 に答える