jQuery 自动完成和 ASP.NET

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/305994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:55:24  来源:igfitidea点击:

jQuery Autocomplete and ASP.NET

asp.netjquerysubsonicautocomplete

提问by djuth

I searched all over this site and the web for a good and simpleexample of autocomplete using jQuery and ASP.NET. I wanted to expose the data used by autocomplete with a webservice (and will probably do that next). In the meantime, I got this working, but it seems a little hacky...

我在整个站点和网络上搜索了一个使用 jQuery 和 ASP.NET 自动完成的简单示例。我想用网络服务公开自动完成使用的数据(接下来可能会这样做)。与此同时,我得到了这个工作,但它似乎有点hacky......

In my page I have a text box:

在我的页面中,我有一个文本框:

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

I am using jQuery autocomplete, set up per their example:

我正在使用 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>

Here is where it starts to get hacky... I call a page instead of a webservice:

这是它开始变得笨拙的地方......我调用页面而不是网络服务:

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

In the page I stripped out ALL of the html and just have this (otherwise, various HTML bits show up in the autocomplete dropdown):

在页面中,我去掉了所有的 html,只有这个(否则,自动完成下拉列表中会显示各种 HTML 位):

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

And in my autocompletetagdata.aspx, I am using SubSonic to query, format and return data from the database (one data item per line):

在我的 autocompletetagdata.aspx 中,我使用 SubSonic 从数据库中查询、格式化和返回数据(每行一个数据项):

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());
}

If you don't do a LIKE query, then it returns everything that contains a match for the character(s) you type -- e.g., typing "a" will include "Ask" and "Answer" as well as "March" and "Mega." I just wanted it to do a starts with match.

如果您不执行 LIKE 查询,则它会返回包含与您键入的字符匹配的所有内容——例如,键入“a”将包括“Ask”和“Answer”以及“March”和“梅加。” 我只是想让它从比赛开始。

Anyway, it works and it's pretty easy to set up, but is there a better way?

无论如何,它有效并且设置起来很容易,但是有没有更好的方法?

采纳答案by bdukes

I just recently implemented autocomplete, and it looks fairly similar. I'm using an ashx (Generic Handler) instead of the aspx, but it's basically the same code in the code behind.

我最近刚刚实现了自动完成,它看起来非常相似。我使用的是 ashx(通用处理程序)而不是 aspx,但它在后面的代码中基本上是相同的代码。

Using the ashx, it'll look something like this:

使用 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;
        }
    }
}

回答by Zachary

I just posted this on another question, but you can override the parse function on the jQuery autocomplete plug-in to make it support any output.

我刚刚在另一个问题上发布了这个,但是您可以覆盖 jQuery 自动完成插件上的 parse 函数以使其支持任何输出。

Example:

例子:

    $("#<%= 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"
    });

All this expects is a string array to XML... Very easy to do... If your using SubSonic, you should check out the RESTHandler (It's a hidden GEM!!!), it supports basic queries on all your objects and can return JSON/XML. Here is an example query using it...

所有这些都需要一个 XML 的字符串数组...很容易做到...如果您使用 SubSonic,您应该查看 RESTHandler(这是一个隐藏的 GEM!!!),它支持对您所有对象的基本查询,并且可以返回 JSON/XML。这是使用它的示例查询...

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

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

If you change list.xml to list.json it will change the results to JSON. The request above will return the a strongly typed "Customer" entity. You can change the parameter to support LIKE, NOT LIKE, etc... Very powerful and all the plumbing is arleady done...

如果您将 list.xml 更改为 list.json,它会将结果更改为 JSON。上面的请求将返回一个强类型的“客户”实体。您可以更改参数以支持 LIKE、NOT LIKE 等...非常强大,所有管道都已完成...

Here is a video on it: http://subsonicproject.com/tips-and-tricks/webcast-using-subsonic-s-rest-handler/

这是关于它的视频:http: //subsonicproject.com/tips-and-tricks/webcast-using-subsonic-s-rest-handler/

回答by tvanfosson

The web service or a WCF service will give you the potential for a better interface. Both can also be set up to do Json serialization.

Web 服务或 WCF 服务将为您提供更好的界面的潜力。两者也可以设置做Json序列化。

Since I'm taking a WCF class as I write (I'm on a break, really!), I'll sketch the WCF method.

由于我在写作时正在学习 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 needs to be Serializable.

LookupTagCollection 需要可序列化。

回答by anthonyvscode

Jquery 1.8 Autocomplete uses "term" not "q" as the querystring param. this is the short and sweet version that I implemented. Hope this helps someone.

Jquery 1.8 自动完成使用“term”而不是“q”作为查询字符串参数。这是我实现的简短而甜蜜的版本。希望这可以帮助某人。

Javascript:

Javascript:

$(function () {
    $("#autocomplete").autocomplete({
        source: "/pathtohandler/handler.ashx",
        minLength: 1,
        select: function (event, ui) {
            $(this).val(ui.item.value);
        }
    });
});

ASHX Handler:

ASHX 处理程序:

public class SearchHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        var term = context.Request.QueryString["term"].ToString();

        context.Response.Clear();
        context.Response.ContentType = "application/json";

        var search = //TODO implement select logic based on the term above

        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        string json = jsSerializer.Serialize(search);
        context.Response.Write(json);
        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}