【问题标题】:jQuery Autocomplete and ASP.NETjQuery 自动完成和 ASP.NET
【发布时间】:2010-09-23 06:56:17
【问题描述】:

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

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

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

这里是它开始变得棘手的地方......我调用一个页面而不是一个网络服务:

  <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 从数据库中查询、格式化和返回数据(每行一个数据项):

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”以及“三月”和“超级”。我只是想让它从匹配开始。

无论如何,它可以工作,而且设置起来很容易,但是有没有更好的方法?

【问题讨论】:

  • 感谢 djuth,这很好用而且非常简单!我不得不承认这是相当有限的,例如,我希望它自动完成一个员工姓名,然后返回一个员工ID,但我可能可以玩弄添加和解析的内容。
  • 现在已弃用并与 JQuery UI 集成 - learningjquery.com/2010/06/autocomplete-migration-guide 显示了如何迁移,而不是太多!

标签: asp.net jquery subsonic autocomplete


【解决方案1】:

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

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

【讨论】:

  • 您在 IIS 中对 ashx 文件的权限是否有问题?我使用了这种方法,当我将应用程序部署到 IIS 6 时,浏览器无法访问 ashx 文件。
  • 我认为新的 jQuery AutoComplete 使用属性“term”而不是“limit”,但这段代码是基于不同的插件。来自 jQuery API 文档:“一个请求对象,具有一个名为“term”的属性,它指的是当前文本输入中的值。例如,当用户在城市字段中输入“new yo”时,自动完成术语将等于“new yo”。 jqueryui.com/demos/autocomplete/#remote
  • limit 是要返回的最大结果数。但是,它可能会发送term 而不是q,本示例使用...
【解决方案2】:

我刚刚在另一个问题上发布了这个,但是您可以覆盖 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。上面的请求将返回一个强类型的“客户”实体。您可以更改参数以支持 LIKE、NOT LIKE 等...非常强大,所有管道都已完成...

这是一个视频:http://subsonicproject.com/tips-and-tricks/webcast-using-subsonic-s-rest-handler/

【讨论】:

  • 这是使用名称/值对处理 XML 的实际答案。上面标记的答案仅适用于显示文本 - 您无法设置/获取值配对。
【解决方案3】:

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 需要可序列化。

【讨论】:

  • 不幸的是,自动完成小部件不需要 JSON,它只需要文本,每个项目都在一个新行上。但是对于看起来不错的 JSON 内容。你会使用什么 URL 来访问它?
【解决方案4】:

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

Javascript:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 2012-06-12
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多